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:
- Installed dependencies. Run
yarn add -D chai cross-env mocha nyc supertest ts-node @types/chai @types/mocha @types/supertest
. - Created a
.mocharc.json
file to configuremocha
. - 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.
- Added a test script in the
package.json
file. I addedtest
script to be run in the CI/CD pipeline, andtest: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!