ben*_*war 3 unit-testing mocha.js node.js sinon should.js
我有一个可能会抛出错误的方法,但是我在编写SinonJS/Mocha/Should单元测试用例时遇到了麻烦.
被测样本函数:
function testError(value) {
if (!value) {
throw new Error('No value');
return false;
}
};
Run Code Online (Sandbox Code Playgroud)
样品测试:
describe('#testError', function() {
it('throws an error', function() {
var spy = sinon.spy(testError);
testError(false);
spy.threw().should.be.true();
});
});
Run Code Online (Sandbox Code Playgroud)
这输出:
#testError
1) throws an error
0 passing (11ms)
1 failing
1) #testError throws an error:
Error: No value
at testError (tests/unit/js/test-error.js:6:14)
at Context.<anonymous> (tests/unit/js/test-error.js:14:6)
Run Code Online (Sandbox Code Playgroud)
我期待Sinon能够抓住错误并允许我对投掷进行间谍活动,但它似乎没有通过测试.有任何想法吗?
我提到不要sinon.js spys捕获错误?但唯一的解决方案是使用expect.如果可能的话,我更愿意使用单个断言库.
nra*_*itz 10
它似乎在try/中起作用catch:
function foo() { throw new Error("hey!"); }
var fooSpy = sinon.spy(foo);
try {
fooSpy();
} catch (e) {
// pass
}
assert(fooSpy.threw());
Run Code Online (Sandbox Code Playgroud)
请注意,你必须打电话fooSpy,而不是 foo自己.
还要注意.should.be.true()是不是兴农的一部分,所以你可能已经在使用柴或类似的库,在这种情况下,expect(foo).to.have.thrown()或assert.throws(foo, someError)语法看起来更漂亮.
更新:如果你正在使用ShouldJS,看起来你可以使用should.throws.我仍然认为这比使用Sinon版本更好.