如何使用 mocha 测试在 nodejs 中抛出异常
How to test of throwing exception in nodejs using mocha
这是我的函数
var EngineAction = function (hostUrl) {
this.parseInput = function (vinNumber, action) {
var requestedAction = ''
if (action === 'START') {
requestedAction = 'START_VEHICLE';
} else if (action === 'STOP') {
requestedAction = 'STOP_VEHICLE';
} else {
throw new Error("input action is not valid");
}
return { id: vinNumber, "action" : requestedAction };
}
}
}
这是摩卡测试:
it('throw error, input for engineAction', function(done) {
var gm = new GM ();
expect(gm.engineAction.parseInput("123", "STATR")).to.throw(Error);
gm.engineAction.parseInput("123", "STATR")).to.throw(Error);
done();
});
我尝试了多种方法,但测试失败并显示消息
1) GM model test throw error, input for engineAction:
Error: input action is not valid
at parseInput (models/gm.js:87:15)
at Context.<anonymous> (test/gm.js:59:25)
这表明方法抛出错误但测试未断言。我错过了什么?
您需要将函数 reference 传递给 expect
。
因为你想用参数调用你的方法,你需要创建一个partial function,预先绑定参数:
expect(gm.engineAction.parseInput.bind(gm, "123", "STATR")).to.throw(Error);
(这使用 gm
作为您方法中的 this
变量,这可能正确也可能不正确)
或者,您可以用另一个函数包装您的方法:
var testFunc = function() {
gm.engineAction.parseInput("123", "STATR"))
};
expect(testFunc).to.throw(Error);
这是我的函数
var EngineAction = function (hostUrl) {
this.parseInput = function (vinNumber, action) {
var requestedAction = ''
if (action === 'START') {
requestedAction = 'START_VEHICLE';
} else if (action === 'STOP') {
requestedAction = 'STOP_VEHICLE';
} else {
throw new Error("input action is not valid");
}
return { id: vinNumber, "action" : requestedAction };
}
}
}
这是摩卡测试:
it('throw error, input for engineAction', function(done) {
var gm = new GM ();
expect(gm.engineAction.parseInput("123", "STATR")).to.throw(Error);
gm.engineAction.parseInput("123", "STATR")).to.throw(Error);
done();
});
我尝试了多种方法,但测试失败并显示消息
1) GM model test throw error, input for engineAction:
Error: input action is not valid
at parseInput (models/gm.js:87:15)
at Context.<anonymous> (test/gm.js:59:25)
这表明方法抛出错误但测试未断言。我错过了什么?
您需要将函数 reference 传递给 expect
。
因为你想用参数调用你的方法,你需要创建一个partial function,预先绑定参数:
expect(gm.engineAction.parseInput.bind(gm, "123", "STATR")).to.throw(Error);
(这使用 gm
作为您方法中的 this
变量,这可能正确也可能不正确)
或者,您可以用另一个函数包装您的方法:
var testFunc = function() {
gm.engineAction.parseInput("123", "STATR"))
};
expect(testFunc).to.throw(Error);