PHPStorm中如何对nodejs项目进行单元测试详解

2020-06-17 06:38:32易采站长站整理

// test example with mocha it is possible to return promise
it('is async', () => {
return new Promise(resolve => resolve(10))
.should.be.fulfilled();
});

// 对象的属性判断
({ a: 10 }).should.have.property('a');
({ a: 10, b: 20 }).should.have.properties({ b: 20 });
[1, 2].should.have.length(2);
({}).should.be.empty();

// 类型检查
[1, 2, 3].should.is.Array();
({}).should.is.Object();

几种常见的测试风格代码举例

BDD

BDD提供的接口有:describe(), context(), it(), specify(), before(), after(), beforeEach(), and afterEach().


describe('Array', function() {
before(function() {
// ...
});

describe('#indexOf()', function() {
context('when not present', function() {
it('should not throw an error', function() {
(function() {
[1, 2, 3].indexOf(4);
}.should.not.throw());
});
it('should return -1', function() {
[1, 2, 3].indexOf(4).should.equal(-1);
});
});
context('when present', function() {
it('should return the index where the element first appears in the array', function() {
[1, 2, 3].indexOf(3).should.equal(2);
});
});
});
});

TDD

提供的接口有: suite(), test(), suiteSetup(), suiteTeardown(), setup(), and teardown():


suite('Array', function() {
setup(function() {
// ...
});

suite('#indexOf()', function() {
test('should return -1 when not present', function() {
assert.equal(-1, [1, 2, 3].indexOf(4));
});
});
});

QUNIT

和TDD类似,使用suite()和test()标记测试永烈,包含的接口有:before(), after(), beforeEach(), and afterEach()。


function ok(expr, msg) {
if (!expr) throw new Error(msg);
}

suite('Array');

test('#length', function() {
var arr = [1, 2, 3];
ok(arr.length == 3);
});

test('#indexOf()', function() {
var arr = [1, 2, 3];
ok(arr.indexOf(1) == 0);
ok(arr.indexOf(2) == 1);
ok(arr.indexOf(3) == 2);
});

suite('String');

test('#length', function() {
ok('foo'.length == 3);
});

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对软件开发网的支持。