【发布时间】:2016-08-11 18:55:02
【问题描述】:
我对单元测试和 TDD 比较陌生,我即将使用 mocha 和 chai 开始我的第一个 TDD 项目。
我应该测试方法的存在和参数长度吗? 如果是这样,有没有比我现在更好的方法呢?感觉非常冗长,尤其是在我的大部分课程中重复此操作时。
为了理解,我设置了一些虚拟测试。
test/index.js
'use strict';
const assert = require('chai').assert;
const Test = require('../lib/index.js');
describe('Test', function() {
it('should be a function without parameters', function() {
assert.isFunction(Test);
assert.lengthOf(Test, 0);
});
let test;
beforeEach(function() {
test = new Test();
});
describe('static#method1', function() {
it('should have static method method1 with 1 parameter', function() {
assert.property(Test, 'method1');
assert.isFunction(Test.method1);
assert.lengthOf(Test.method1, 1);
});
it('should assert on non-string parameters', function() {
const params = [
123,
{},
[],
function() {}
];
params.forEach(function(param) {
assert.throws(function() {
Test.method1(param)
});
});
});
it('should return "some value"', function() {
assert.equal(Test.method1('param'), 'some value')
});
});
describe('method2', function() {
it('should have method method2 with 2 parameters', function() {
assert.property(test, 'method2');
assert.isFunction(test.method2);
assert.lengthOf(test.method2, 2);
});
it('should assert on non-number parameters', function() {
const params = [
'some string',
{},
[],
function() {}
];
params.forEach(function(param) {
assert.throws(function() {
test.method2(param)
});
});
});
it('should add the parameters', function() {
assert.equal(test.method2(1, 2), 3);
assert.equal(test.method2(9, -2), 7);
assert.equal(test.method2(3, -12), -9);
assert.equal(test.method2(-7, -5), -12);
})
});
});
以及经过测试的实现。
lib/index.js
'use strict';
const assert = require('chai').assert;
exports = module.exports = (function() {
class Test {
static method1(param0) {
assert.typeOf(param0, 'string');
return 'some value';
}
method2(param0, param1) {
assert.typeOf(param0, 'number');
assert.typeOf(param1, 'number');
return param0 + param1;
}
}
return Test;
}());
【问题讨论】:
-
在某些情况下测试函数签名是可以的,但在某些情况下,它可能真的很难维护,并且可能会在每次 API 更改时频繁中断测试,从而阻碍进一步的开发,即使只是以附加的方式。当参数顺序很重要(包含在 async.waterfall 中的函数等)时,它可以产生一些好处,但总的来说我还没有发现它很有用。但是,使用 sinonjs.org 之类的东西来测试这些函数的运行时效果要容易得多。我会看看间谍和存根/模拟,因为它们在这里真的可以提供帮助。
-
非常感谢您的回答,我一定会看看SinonJs。
标签: node.js unit-testing tdd mocha.js chai