Hello, I hope you are having a good week.

I continue my assignment on setting up CI/CD. Today I would like to tell you about how I setup test on the GitHub Actions. Now, I need to set up a test for a back end built with Node.js, TypeScript and Express. I used chai as an assertion library, SuperTest to run the back end server to be tested, and Istanbul to count the test coverage.

Here are the steps I did:

  1. Installed dependencies. Run yarn add -D chai cross-env mocha nyc supertest ts-node @types/chai @types/mocha @types/supertest.
  2. Created a .mocharc.json file to configure mocha.
  3. Created a sample test. You can add a health check endpoint if you don’t have one. It is a best practice to make other services such as monitoring system can check whether you application is alive or not. Just return HTTP status code 200 as a response is enough.
  4. Added a test script in the package.json file. I added test script to be run in the CI/CD pipeline, and test:watch script to be run in development environment, to provide the developer that interested in test driven development.
// .mocharc.json
{
  "require": ["ts-node/register"]
}
// app.test.ts
import { expect } from "chai";
import request from "supertest";
import app from "./app";

describe("Health check endpoint", () => {
  it("should response with HTTP status code 200", () => {
    request(app)
      .get("/health")
      .end((error, response) => {
        if (error) {
          throw error;
        }

        expect(response.status).eq(200);
      });
  });
});
// ... the rest of the package.json
{
  "scripts": {
    "test": "cross-env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' NODE_ENV=test nyc --reporter=lcov --extension .ts mocha --forbid-only src/**/*.test.ts",
    "test:watch": "cross-env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' NODE_ENV=test mocha --watch --watch-files src src/**/*.test.ts"
  }
}
name: πŸ† Code Quality

on:
  push:
    branches:
      - main
  pull_request:

jobs:
  code-quality:
    name: πŸ† Code quality
    runs-on: ubuntu-latest
    steps:
      - name: ⬇️ Checkout repo
        uses: actions/checkout@v4

      - name: βŽ” Setup node
        uses: actions/setup-node@v3
        with:
          node-version: 20
          cache: yarn

      - name: πŸ“¦ Install deps
        run: yarn --immutable

      - name: πŸ•΅οΈβ€β™‚οΈ Test
        run: yarn test

That’s all from me. I hope you can get some ideas on how to set up tests for back end that are written in TypeScript and using Express and run them in GitHub Actions.

Thank you!