Search code examples
node.jsexpresschaichai-http

How to launch a chai test in node?


I have a node/typescript application. I'm trying to test routes with chai and chai-http. I can launch a file when I write an explicit name: yarn test myroute.test.ts, but yarn test at the root does nothing.

Also, the test is never performed. I only receive a Done in 0.06s. in my terminal. No "passed" or "failed".

Here is the test:

import chai from "chai";
import chaiHttp from "chai-http";
import { server } from "../index";

chai.use(chaiHttp);
const chaiApi = chai.request(server);
describe("GET /user/:id", () => {
  it("return user information", async () => {
    const res = await chaiApi
      .get("/user/123")
      .set("Cookie", "_id=567;locale=en");
    chai.assert.equal(res.status, 200);
  });
});

the package.json script is: "test": "test". I assume it's completely wrong, but chai doc says nothing about what to write here.


Solution

  • chai is an assertion library, similar to Node's built-in assert. It does NOT contain a test runner. You need to use mocha to collect and run your declared test suites and test cases.

    After adding the mocha test framework, you can declare npm test script like this:

    "test": "mocha --require ts-node/register --timeout 5000",
    

    In order to run the TS test file, we need to specify ts-node/register. Use it like this:

    yarn test myroute.test.ts