My blog: JavaScript Unit Testing Framework

Introduction to the

Testing is an important link to ensure the quality of code. Although the unit test of Web project cannot completely complete the function test, it can guarantee the working quality of the bottom single module and guarantee the external interface will not change during the code reconstruction.

The test framework

  • Mocha
  • Jasmine
  • Jest
  • Tape
  • Karma

Mocha

Mocha is a flexible testing framework, but it is just a structure, and you need to introduce other plug-ins to implement some of the testing capabilities, such as assertion libraries, coverage statistics, and so on.

Mocha is installed

NPM install mocha –save-dev

Script syntax

A brief example:

// introduce the module or class to be tested const add = require("./add");
const assert = require("assert"); // describe: Define a set of tests describe("Addition function test".function() {
    before(function() {
        // runs before all tests inthis block }); // it: Define a test case"One plus one should make two.".function() {// Assert: Nodejs built-in assert module assert.equal(add(1, 1), 2); }); after(function() {
        // runs after all test in this block
    });
});
Copy the code

Method of use

Create the test-mocha directory for the test scripts, named in the style of [module name].test.js, and then configure the test commands in package.json:

"scripts": {
    "test-mocha": "mocha test-mocha/"
}
Copy the code

NPM run test-mocha will output the test result as shown below:

Assertions library

Mocha supports assertion libraries such as should.js, CHAI, expect. Js, Better-Assert, Unexpected, etc. In the example above, we can compare the differences between each assertion library:

  • assert
assert.ok(add(1, 1));
assert.equal(add(1, 1), 2);
Copy the code
  • should.js
(add(1, 1)).should.be.a.Number();
(add(1, 1)).should.equal(2);
Copy the code
  • expect.js
expect(add(1, 1)).to.be.a("number");
expect(add(1, 1)).to.equal(2);
Copy the code
  • Chai: Supports should, expect, and Assert syntax

In conclusion, compared with assert, should.js and expect. Js have stronger semantics and support type detection, while should.js is more concise in syntax and supports chained syntax.

hooks

Mocha supports four hooks, including before/after/beforeEach/afterEach.

Asynchronous test

By default, Mocha executes 2000ms for each test case, and an error will be reported if the duration exceeds. Therefore, if there is an asynchronous operation in the test code, the done function should be used to specify the end of the test case. Done accepts the Error argument.

BOM/DOM

When Mocha runs in the Node environment, it does not support BOM and DOM interfaces, and requires the introduction of jsDOM and jDOM-Global libraries.

Jasmine

Jasmine is a full-featured testing framework with built-in assertions Expect; However, global declarations and configuration are more complex and less flexible to use.

Jasmine is installed

NPM install jasmine –save-dev

Script syntax

const add = require(".. /src/add");

describe("Addition function test".function () {
    it("One plus one equals two.".function() {
        expect(add(1, 1)).toEqual(2);
    });
    it("Output number".function() {
        expect(add(1, 1)).toEqual(jasmine.any(Number));
    });
});
Copy the code

Jasmine’s syntax is very similar to Mocha’s, but the assertions use built-in Expect ().

Method of use

New configuration file jasmine. Json:

{// Test the relative path of the script"spec_dir": "test-jasmine"// Test the script"spec_files": [
        "*.test.js"
        ! "" *.notest.js"], // Scripts to be imported before testing"helpers": [], // Whether to stop testing after the first error"stopSpecOnExpectationFailure": false, // Whether tests are executed in semi-random order"random": false
}
Copy the code

Create test script directory test-jasmine, name the script file [module name].test.js, and configure the test command in package.json:

"scripts": {
    "test-jasmine": "jasmine --config=jasmine.json"
}
Copy the code

Then execute NPM run test-jasmine, and output the test result as shown below:

The hooks and asynchronous

Similar to Mocha.

Jest

Jest is a full-featured “zero configuration” testing framework that integrates tools and requires no configuration to use.

Jest installation

NPM install –save-dev jest

Script syntax

Jest syntax is not quite the same as the above two frameworks:

const add = require(".. /src/add");

describe("Addition function test", () = > {test("One plus one equals two.", () => {
        expect(add(1, 1)).toBe(2);
    }); 
});

Copy the code

Jest defines a test case with Test, and comes with assertion Expect. The assertion library is powerful, but the syntax is more complex than that of should.js.

Assertion syntax:

  • Normal matching:toBe.not.toBe
  • An empty match:toBeNull.toBeUndefined.toBeDefine.toBeTruthy.toBeFalsy
  • Number size:toBeGreaterThan.toBeGreaterThanOrEqual.toBeLessThan.toEqual.toBeCloseTo(for floating point numbers)
  • Regular matching:toMatch
  • Array query:toContain
  • Structure matching:toEqual(expect.any(constructor))

Method of use

Create test script directory test-jest, name the script file [module name].test.js, and configure the test command in package.json:

"scripts": {
    "test-jest": "jest test-jest/"
}
Copy the code

Then execute NPM run test-jest and output the test result as follows:

hook

Jest there are four hooks, same beforeAll beforeEach / / afterEach afterAll.

BOM/DOM

Jest has built-in support for DOM and BOM interfaces.

Coverage statistics

Jest has built-in coverage statistics. To facilitate the configuration, we can create a configuration file named Jest.config.js:

Module. exports = {// enable collectCoverage:true, // Specify the file to overwrite collectCoverageFrom: ["src/*.js"], // Specify a coverageDirectory for output coverage statistics:"test-jest/coverage/"// Specify the test scripttestMatch: [
    	"**/test-jest/*.test.js"]};Copy the code

Then change the name of package.json to “test-jest”: “jest”.