Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Software testing -- getting started with mocha


May 30, 2021 Article blog


Table of contents


What is TDD:

TDD:Test driven devlement, test-driven development, is a core practice and technique in agile development, as well as a design methodology. The principle of TDD is to write unit test case code before developing functional code, which determines what product code needs to be written.

What is mocha:

Mocha is a unit test framework for JavaScript that can run in both browser and Node .js environments.

Install mocha:

1. Create a project.

2. Run:

#初始化
npm init
#安装mocha
npm i mocha chai -D

At this point, the directory structure is:

 Software testing -- getting started with mocha1

Write business code:

Writing math .js is used to simulate business code

function add(x,y){
    return x+y;
}

function multiply (x,y){
    return x*y;
}

module.exports={
    add,multiply 
}

Write test code:

//导入刚刚写的math.js
var math=require("../math");
//导入断言
var assert= require("assert");
// 描述测试文件
describe('测试math.js',function(){
    // 描述测试的方法
    describe('测试方法add',function(){
        // mocha提供了it方法,称为测试用例,表示一个单独的测试
        // 我们可以写某个方法的多个测试用例来测试不同情况下的状况
        // 测试10+1;
        it('10+1',function(){
            // 断言10+1=11
            assert.equal(math.add(10,1),11);
        });
        // 测试不通过
        // 测试10+2;断言10+2=9
        it("10+2",function(){
            assert.equal(math.add(10,2),9)
        })
    });
    describe("测试方法multiply",function(){
        // 测试5*2
        it('5-2',function(){
            // 断言5*2=10
            assert.equal(math.multiply(5,2),10);
        })
    });
})

Configure package.json:

The direct use of mocha tests is displayed in the terminal

"scripts": {
    "test": "mocha"
  }

Run the test:

npm test

outcome:

 Software testing -- getting started with mocha2

Recommended lessons:

Vue .js three days of hands-on tutorials

JavaScript Live: Dynamic website development

Javascript mobile app live development

Node .js micro-classes

Software testing tutorials