Skip to content

Instantly share code, notes, and snippets.

@loftywaif002
Last active June 19, 2023 17:20
Show Gist options
  • Save loftywaif002/d72f1d7d6a557ef92e2739e6740ce1d9 to your computer and use it in GitHub Desktop.
Save loftywaif002/d72f1d7d6a557ef92e2739e6740ce1d9 to your computer and use it in GitHub Desktop.
How to setup chai, mocha and nyc for testing Node.js api server. [with code coverage report]

How to setup chai, mocha and nyc for Node.js server, with code coverage report.

Add the following testing packages in package.json file

 "dependencies": {
    "chai": "^4.2.0",
    "chai-http": "^4.3.0",
    "mocha": "^7.1.0",
    "mocha-junit-reporter": "^1.23.3",
    "mocha-multi-reporters": "^1.1.7",
  },
  "devDependencies": {
    "cross-env": "^7.0.2"
  }
  • If mocha version > 8.0.0, add a file called .mocharc.json
{
  "require": "ts-node/register",
  "recursive": true,
  "reporter": "mocha-multi-reporters",
  "reporterOptions": {
    "reporterEnabled": "spec, mocha-junit-reporter",
    "mochaJunitReporterReporterOptions": {
      "mochaFile": "unit.xml",
      "mochaFileTitle": "Unit Tests",
      "xmlVersion": "1.0"
    }
  }
}
  • Add test coverage report, we can use nyc npm package

    • npm install nyc --save-dev
  • Create a file called .nycrc and add the following:

{
  "include": ["src/**/*.ts"],
  "exclude": ["src/tests/**/*.spec.ts"],
  "reporter": ["lcov", "text"],
  "report-dir": "coverage",
  "temp-dir": ".nyc_output",
  "all": true
}

Using nyc will create a coverage report inside coverage/lcov-report/index.html. We can add an endpoint "/test-coverage" and use hbs module to have a template and serve index.html.

  • Install hbs
npm install hbs --save
  • Create a folder called views in the root directory and then create a file called coverage.hbs and add the following code in it.
<!DOCTYPE html>
<html>
  <head>
    <title>Test Coverage</title>
  </head>
  <body>
    <h1>Test Coverage Report</h1>
    {{{report}}}
  </body>
</html>

  • Then, add the following code in app.ts / server.js / index.js file where app = express() is defined.
import hbs from "hbs";
import fs from "fs";
import path from "path";


app.engine(".hbs", hbs.__express);
app.set("view engine", ".hbs");


app.get("/test-coverage", (req: Request, res: Response) => {
  const coverageReportPath = path.join(__dirname, "..", "coverage", "lcov-report", "index.html");
  fs.readFile(coverageReportPath, "utf8", (err, data) => {
    if (err) {
      console.error("Error reading coverage report:", err);
      return res.status(500).send("Error reading coverage report");
    }
    res.render("coverage", { report: data });
  });
});
  • Add the following in you scripts section of package.json file
"test": "cross-env PORT=8001 nyc ./node_modules/.bin/mocha --require ts-node/register 'src/tests/**/*.spec.ts' --exit --reporter mocha-junit-reporter --reporter-options mochaFile=unit.xml"

After running the server, we can visit /test-coverage endpoint and see the code coverage report.

How to setup chai, mocha and nyc for Node.js server, with code coverage report.

Add the following testing packages in package.json file

 "dependencies": {
    "chai": "^4.2.0",
    "chai-http": "^4.3.0",
    "mocha": "^7.1.0",
    "mocha-junit-reporter": "^1.23.3",
    "mocha-multi-reporters": "^1.1.7",
  },
  "devDependencies": {
    "cross-env": "^7.0.2"
  }
  • If mocha version > 8.0.0, add a file called .mocharc.json
{
  "require": "ts-node/register",
  "recursive": true,
  "reporter": "mocha-multi-reporters",
  "reporterOptions": {
    "reporterEnabled": "spec, mocha-junit-reporter",
    "mochaJunitReporterReporterOptions": {
      "mochaFile": "unit.xml",
      "mochaFileTitle": "Unit Tests",
      "xmlVersion": "1.0"
    }
  }
}
  • Add test coverage report, we can use nyc npm package

    • npm install nyc --save-dev
  • Create a file called .nycrc and add the following:

{
  "include": ["src/**/*.ts"],
  "exclude": ["src/tests/**/*.spec.ts"],
  "reporter": ["lcov", "text"],
  "report-dir": "coverage",
  "temp-dir": ".nyc_output",
  "all": true
}

Using nyc will create a coverage report inside coverage/lcov-report/index.html. We can add an endpoint "/test-coverage" and use hbs module to have a template and serve index.html.

  • Install hbs
npm install hbs --save
  • Create a folder called views in the root directory and then create a file called coverage.hbs and add the following code in it.
<!DOCTYPE html>
<html>
  <head>
    <title>Test Coverage</title>
  </head>
  <body>
    <h1>Test Coverage Report</h1>
    {{{report}}}
  </body>
</html>

  • Then, add the following code in app.ts / server.js / index.js file where app = express() is defined.
import hbs from "hbs";
import fs from "fs";
import path from "path";


app.engine(".hbs", hbs.__express);
app.set("view engine", ".hbs");


app.get("/test-coverage", (req: Request, res: Response) => {
  const coverageReportPath = path.join(__dirname, "..", "coverage", "lcov-report", "index.html");
  fs.readFile(coverageReportPath, "utf8", (err, data) => {
    if (err) {
      console.error("Error reading coverage report:", err);
      return res.status(500).send("Error reading coverage report");
    }
    res.render("coverage", { report: data });
  });
});
  • Add the following in you scripts section of package.json file
"test": "cross-env PORT=8001 nyc ./node_modules/.bin/mocha --require ts-node/register 'src/tests/**/*.spec.ts' --exit --reporter mocha-junit-reporter --reporter-options mochaFile=unit.xml"

After running the server, we can visit /test-coverage endpoint and see the code coverage report.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment