38.Jest单元测试?
创建名为unit-testing-functions目录
切换到该目录cd unit-testing-functions并且初始化该JavaScript项目:npm init--yes
现在在该目录你应该有一个package.json文件
安装Jest:nom i jest --save-dev
你现在可以验证Jest是否安装成功通过运行:./node_modules/.bin/jest -v
// 引入要测试的函数
const sum = require('./sum.js');
// describe即定义了测试单元
describe('sum suite', function () {
// test(...)即是我们添加的第一个单元测试。
test('should add 2 positive numbers together and return the result', function () {
expect(sum(1, 2)).toBe(3); // toBe 被称作为“匹配器(matcher)
这是任何单元测试的构建块,被称作为“断言(assertion)”。
断言基本上是一种表达对事物应该如何表现的期望的方式。
在我们的示例中,我们期望调用 sum(1, 2) 应该返回的结果是 3 。
});
});
运行单元测试
配置package.json
"scripts": {
"test": "jest"
}
运行 npm run test