May 30, 2021 Article blog
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.
Mocha is a unit test framework for JavaScript that can run in both browser and Node .js environments.
1. Create a project.
2. Run:
#初始化
npm init
#安装mocha
npm i mocha chai -D
At this point, the directory structure is:
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
}
//导入刚刚写的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);
})
});
})
The direct use of mocha tests is displayed in the terminal
"scripts": {
"test": "mocha"
}
npm test
outcome:
Recommended lessons:
Vue .js three days of hands-on tutorials
JavaScript Live: Dynamic website development
Javascript mobile app live development