我写了一个有向无环图,可是无法验证我写的代码时正确的。因此引入单元测试,选择mocha是由于比较多人用。文档比较全html
代码示例
import { expect } from 'chai';
import chai from 'chai';
const should = chai.should();
import { isDag } from '../utils/IsDAG';
describe('是不是有向无环图测试', function() {
this.timeout(50000); // 异步请求须要设置超时时间,否则会报超时错误
it('是Dag测试', function(done) {
const graph = [
{
source: 1,
target: 2
},
{
source: 1,
target: 3
}
];
const result = isDag(graph);
expect(result).to.equal(true);
done();
});
it('异步请求测试', function(done) {
const graph = [
{
source: 1,
target: 2
},
{
source: 1,
target: 3
}
];
setTimeout(() => {
const result = isDag(graph);
expect(result).to.equal(true);
done();
}, 2000);
});
it('不是Dag测试-没有根节点', function(done) {
const graph = [
{
source: 1,
target: 2
},
{
source: 2,
target: 3
},
{
source: 3,
target: 1
}
];
const result = isDag(graph);
result.should.equal(false);
done();
});
it('是Dag测试-只有一个点', function(done) {
const graph = [
{
source: 1
}
];
const result = isDag(graph);
if (result) {
done();
} else {
done('错误');
}
});
});
复制代码
断言库expect和should对比node
一、expect的实现侵入性比较低,expect方法会返回一个代理对象,上面绑定了一些能够用来进行断言的方法。
二、should的实现是将should一类的方法直接注入到全部的对象里,破坏性比较高。若是你本身定义了一些和should一类同名的方法就悲剧了es6
引用expect和should断言库
var chai = require('chai')
, expect = chai.expect
, should = chai.should();
// Or
import { expect } form 'chai';
import chai.should(); form 'chai';
const should = chai.should();
// 使用expect
expect(foo).to.be.a('string');
expect(foo).to.equal('bar');
expect(foo).to.have.lengthOf(3);
// 使用should
foo.should.be.a('string');
foo.should.equal('bar');
foo.should.have.lengthOf(3);
复制代码
nyc使用npm
if (window.mochaPhantomJS) { mochaPhantomJS.run(); }
else { mocha.run(); }
复制代码