Javascript 为什么抛出异常的函数不使用函数\ u name.should.throw传递(错误)?
我们有以下工作测试示例:Javascript 为什么抛出异常的函数不使用函数\ u name.should.throw传递(错误)?,javascript,unit-testing,mocha.js,chai,Javascript,Unit Testing,Mocha.js,Chai,我们有以下工作测试示例: "use strict"; var should = require("chai").should(); var multiply = function(x, y) { if (typeof x !== "number" || typeof y !== "number") { throw new Error("x or y is not a number."); } else return x * y; }; describe("Multipl
"use strict";
var should = require("chai").should();
var multiply = function(x, y) {
if (typeof x !== "number" || typeof y !== "number") {
throw new Error("x or y is not a number.");
}
else return x * y;
};
describe("Multiply", function() {
it("should multiply properly when passed numbers", function() {
multiply(2, 4).should.equal(8);
});
it("should throw when not passed numbers", function() {
(function() {
multiply(2, "4");
}).should.throw(Error);
});
});
没有解释为什么第二个测试需要与黑客一起运行
(function() {
multiply(2, "4");
}).should.throw(Error);
如果你像这样运行它
it("should throw when not passed numbers", function() {
multiply(2, "4").should.throw(Error);
});
测试失败了
Multiply
✓ should multiply properly when passed numbers
1) should throw when not passed numbers
但将函数作为常规节点脚本运行会失败:
Error: x or y is not a number.
at multiply (/path/test/test.js:7:11)
所以我不明白为什么应该
没有发现它抛出错误的事实
什么原因导致需要将其包装在匿名
function(){}
call中?它对异步运行的测试、作用域或其他东西有用吗 Chai是常规JavaScript,而不是魔法。如果您有一个表达式a().b.c()
和a
抛出,则c()
无法捕捉它<代码>c甚至无法运行。引擎甚至不知道c
是什么,因为a
没有返回一个可以查找.b.c
的值;它抛出了一个错误。当您使用函数时,您有一个要查找的对象。should
,这反过来会给您一个要查找并调用。throw
的对象
这就是为什么它不能做到这一点,但从API的角度来看,没有什么错:.should.throw
只是对函数的断言,而不是函数调用
我还建议使用Chai的expect
,它不会将自身插入Object.prototype
中,从而呈现出神奇的外观