Use mocha and should library to do nodejs unit test

    Nodejs is server-side development, he can also do unit testing, but this unit test is generally for a certain file or a module, we often see that many projects on github have many xxx in their respective folders. A file like test.js is usually a unit test for a xxx.js module in the corresponding folder. Nodejs unit test has mocha library, he provides describe, it and other syntax to do the test. In addition, the assert library of nodejs itself provides the assertion function. You can also use the should library to make assertions, and the chai dependent library can also make assertions.

    1. Create a nodejs project and add dependencies

mkdir mochatest
cd mochatest
npm init -y
npm install mocha should -D

    Modify the test command in the scripts script:

{
  "name": "mochatest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha test.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "mocha": "^7.0.0",
    "should": "^13.2.3"
  }
}

    Second, write a module app.js

const add = (a,b)=>a+b
const sub = (a,b)=>a-b
const reducer = (a)=>a.reduce((x,y)=>x+y,0)
module.exports = {add,sub,reducer}

    Three, write test code

require("should")
var app = require("./app")
var assert = require("assert")
describe("mocha unit test",function(){
    it("1+2=3",function(){
        app.add(1,2).should.equal(3)
    })

    it("8-5=3",function(){
        app.sub(8,5).should.equal(3)
    })

    it("[1 2 3 4 5].reduce()=15",function(){
        app.reducer([1,2,3,4,5]).should.equal(15)
    })

    it("assert.equal(5,add(2,3))",function(){
        assert.equal(5,app.add(2,3))
    })
    
})

    Fourth, run the test npm run test

   

    In the example, we used should to make assertions in the first three use cases. The last example uses the assert of nodejs to make assertions. This built-in assertion is similar to the unit test assertion that comes with java. The usage is also very simple and familiar with java development. It should be easier to understand. The assert assertion is very intuitive. Generally, when doing equal judgment, an actual value and an expected value are passed in. If the two are equal, the use case test passes and displays pass.

    Nodejs unit testing is much more than this, and there are tests for setTimeout delay, async, HTTP network requests, etc., all have related test skills. Only when the unit test is done well, we will develop more robust and stable Code. Subsequent integration tests will also have fewer errors.

Published 529 original articles · praised 287 · 1.47 million views

Guess you like

Origin blog.csdn.net/feinifi/article/details/103972302