内容简介:我写了一个有向无环图,但是没法验证我写的代码时正确的。所以引入单元测试,选择mocha是因为比较多人用。文档比较全所以在"test": "nyc mocha --require @babel/register -R spec src/test"加上@babel/register
我写了一个有向无环图,但是没法验证我写的代码时正确的。所以引入单元测试,选择mocha是因为比较多人用。文档比较全
参考文档
使用过程
-
安装mocha nyc npm i nyc @babel/register mocha --save-dev
-
在package.json中的scripts上添加"test": "nyc mocha --require @babel/register -R spec src/test",这样运行npm run test 就能运行test文件夹下的所有测试文件
-
在test文件夹下新建 IsDAG.test.js文件 (通常,测试脚本与所要测试的源码脚本同名,但是后缀名为.test.js),写测试代码,因为node自带的断言库不好用,所以可以使用chai断言库
-
写完后运行npm run test发现报错了 import不存在。原因是 mocha是node的构建工具,默认只支持commonJS的模块系统,引入@babel/register "test": "nyc mocha --require @babel/register -R spec src/test"。
所以在"test": "nyc mocha --require @babel/register -R spec src/test"加上@babel/register
import { expect } from 'chai';
import { isDag } from '../index';
// describe块称为"测试套件"(test suite),表示一组相关的测试。它是一个函数,第一个参数是测试套件的名称("加法函数的测试"),第二个参数是一个实际执行的函数。
describe('是否是有向无环图测试', function() {
// it块称为"测试用例"(test case),表示一个单独的测试,是测试的最小单位。它也是一个函数,第一个参数是测试用例的名称("1 加 1 应该等于 2"),第二个参数是一个实际执行的函数。
it('是Dag测试', function (done) {
const graph = [
{
source: 1,
target: 2,
},{
source: 1,
target: 3
}
]
const result = isDag(graph);
if(result) {
// 正确返回done
done()
}else {
// 错误返回错误信息
done('错误');
};
});
});
在vscode上断点调试
- 选择mocha文件测试
- 编写配置文件,(如何把nyc命令加进来我就不知道了)
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Mocha Tests",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha", // mocha的位置
"args": [ // 运行的命令
"--require",
"@babel/register",
"-R",
"spec",
"${workspaceFolder}/src/test" // 测试文件都位置
],
"internalConsoleOptions": "openOnSessionStart"
}
]
}
- 添加断定调试
以上所述就是小编给大家介绍的《记一次使用mocha做单元测试》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- Vue 应用单元测试的策略与实践 02 - 单元测试基础
- Vue 应用单元测试的策略与实践 04 - Vuex 单元测试
- Vue 应用单元测试的策略与实践 03 - Vue 组件单元测试
- Angular单元测试系列-Component、Directive、Pipe 以及Service单元测试
- 单元测试,只是测试吗?
- 单元测试和集成测试业务
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Iterative Methods for Sparse Linear Systems, Second Edition
Yousef Saad / Society for Industrial and Applied Mathematics / 2003-04-30 / USD 102.00
Tremendous progress has been made in the scientific and engineering disciplines regarding the use of iterative methods for linear systems. The size and complexity of linear and nonlinear systems arisi......一起来看看 《Iterative Methods for Sparse Linear Systems, Second Edition》 这本书的介绍吧!