Implementing TS unit testing using Mocha testing framework

Posted by vchris on Fri, 17 Sep 2021 13:11:30 +0200

1. Background

 

The current project uses ts as the development language. If you want to introduce unit testing, choose Mocha, one of the mainstream frameworks after Baidu to try.

2. Mocha introduction

mocha is a unit test framework of JavaScript, which can run in both browser environment and Node.js environment.

With mocha, we just need to focus on writing the unit test itself, and then let Mocha automatically run all the tests and give the test results.

mocha features:

  1. You can test both simple JavaScript functions and asynchronous code, because asynchrony is one of the characteristics of JavaScript;

  2. All tests can be run automatically, or only specific tests can be run;

  3. You can support before, after, before each, and after each to write initialization code.

Mocha Chinese network - interesting, simple and flexible javascript testing frameworkhttps://mochajs.cn/

 

3. Environment configuration

Install Mocha and assertion library chai

You need to install both globally and locally

npm install --global mocha
npm install --save mocha
npm install --global chai
npm install --save chai
npm install -D '@types/chai' '@types/mocha' '@types/node' '@types/sinon'
npm install -D mocha chai cross-env nyc sinon ts-node tsconfig-paths

 

After installation, let's add the required configuration:

Add mocha configuration: open package.json, add a mocha field and add a new scripts command, as follows:

{
  "scripts": {
    "test": "cross-env TS_NODE_PROJECT='test/tsconfig.test.json' mocha test/**/**.test.ts",
    "cover": "nyc --reporter=html npm run test"
  },
  "mocha": {
    "require": [
      "ts-node/register",
      "tsconfig-paths/register"
    ],
    "ui": "bdd"
  }
}

ts node / register is used to execute ts test code, while tsconfig paths / register is used to resolve the path alias configured in tsconfig.

Configure the test environment tsconfig: next, we create a new test folder, where all subsequent test cases can be written, and then create tsconfig.test.json and fill in the following contents:

{
    "extends": "../tsconfig.json",
    "ts-node": {
        "transpileOnly": true
    }
}

The extensions here point to tsconfig.json in the root directory. But in fact, it needs to be set according to needs. Personally, I don't think this extensions is necessary, because there may be holes in the tsconfig in the project.

At this point, the configuration is complete.

Test case example. Here is a simple reference to the source of testfunc.ts simulation interface:


import { expect } from 'chai'
// import { spy } from 'sinon'
import { add, cal} from './src/testfunc';


describe('test index.js', () => {
    before(() => console.info("Execute before all test cases in this block"))

    after(() => console.info("Execute after all test cases in this block"))

    beforeEach(() => console.info("Execute before each test case in this block"))

    afterEach(() => console.info("Execute after each test case in this block"))

    describe('test addNum function', () => {
        it('The result of adding two numbers is the sum of two numbers', () => {
            expect(add(1, 2)).to.be.equal(3);
        })
    })
    describe('test addNum function', () => {
        it('The result of adding two numbers is the sum of two numbers', () => {
            expect(cal(1, 2)).to.be.equal(5);
        })
    })
})

testfunc.ts:

import { multiply } from "./testFunc2";

export function add(a: number, b: number): number {
    return a + b;
}

export function cal(a: number, b: number): number {
    return add(a, b) + multiply(a, b);
}

The results are as follows:

  So far, the whole process of unit testing the interface function of TS project using mocha as the testing framework has basically been completed

Pit encountered:

1. For mocha and chai installation, both global+dev+-D and @ types/mocha dependency packages should be installed. Otherwise, the npm command cannot be executed.

2. The module in compilerOptions in tsconfig cannot be set to esnext. If it is not necessary, please do not refer to tsconfig in the root directory (personal understanding).

Topics: Java TypeScript unit testing