In this post, I’ll add unit tests to the example application that I’ve been fiddling around with in the recent posts.

Folder structure

In the previous post, I added some functional tests with WebdriverIO. They were stored in the folder test/specs. I’d like to keep the unit test separate from the functional tests, so I’ll rename the old folder to test/functional-specs and store the new unit tests under test/unit-specs.

Dependencies

I’ll install these dev dependencies (with npm install --save-dev):

  • mocha: the test framework
  • chai: an assertion library
  • sinon: a library for spies, stubs and mocks
  • proxyquire: a library for dependency injection

npm scripts

I’ll setup two npm scripts. One that produces plain text output (for local usage) and one that produces XML report that the CI server can read. This needs to be added to package.json:

  "test": "mocha ./test/unit-specs",
  "test-junit": "mocha -R xunit --reporter-options output=test-reports/ci-mocha.xml ./test/unit-specs",

Note that the first one works with simply npm test but the second one is invoked with npm run test-junit.

Adding the first test

The entire code base consists of a single file, index.js. I’ll add a unit test in ./test/unit-specs/index.js and I’ll unit test the feature provided by the version endpoint. You can see the unit test here.

TeamCity

In TeamCity, we need to run the unit tests in the Commit Stage:

docker run \
    --rm -v $(pwd)/test-reports:/app/test-reports \
    blog-helm-ci:%env.IMAGE_TAG% \
    npm run test-junit

The XML test report gets consumed and the tests are presented in the Test tab:

Visual Studio Code

One last bit is to configure Visual Studio Code so that I can run and debug the tests from within the editor. Visual Studio Code has a template configuration for running mocha tests and all I had to set is the path where the unit tests live. My entire .vscode/launch.json file is around 30 lines:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Mocha Tests",
            "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
            "args": [
                "-u",
                "tdd",
                "--timeout",
                "999999",
                "--colors",
                "${workspaceFolder}/test/unit-specs"
            ],
            "internalConsoleOptions": "openOnSessionStart"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceFolder}\\index.js"
        }
    ]
}