Software Testing-Getting Started with Mocha

Software Testing-Getting Started with Mocha

What is TDD:

TDD: Test driven development, is a core practice and technology in agile development, as well as a design methodology.

The principle of TDD is to write unit test case code before developing functional code, and the test code determines what product code needs to be written.

What is mocha:

Mocha is a unit testing framework for JavaScript, which can be run in a browser environment or in a Node.js environment.

Install mocha:

1. Create a project.

2. Run:

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

The directory structure at this time is:
Insert picture description here

Write business code:

Write math.js 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:

Directly use mocha to test and display in the terminal

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

Run the test:

npm test

result:

Insert picture description here

Guess you like

Origin blog.csdn.net/Meetsummer/article/details/112396927