我试图用karma和sinon来存根一个全局函数。我有这个功能
// lib/hello.js
var hello = function () {
return 'hello';
};
var throwFunction = function () {
throw 'throwFunction was called';
};
var callThrowFunction = function (arg) {
throwFunction(arg);
};
和这个测试
// test/test_lib.js
describe('test lib', function () {
it('test hello', function () {
assert.strictEqual(hello(), 'hello');
});
it('throwFunction', function () {
var stubFunction = sinon.stub(window, 'throwFunction');
window.throwFunction();
assert(stubFunction.called);
stubFunction.restore();
});
it('callThrowFunction', function () {
var stubFunction = sinon.stub(window, 'throwFunction');
window.callThrowFunction('some arg');
stubFunction.restore();
});
});
当我打电话给业力时,前两个测试运行正常,但在第三个测试中我无法存根函数throwFunction
并调用throw
。
karma start --single-run --reporters=spec
test lib
✓ test hello
✓ throwFunction
✗ callThrowFunction
the string "throwFunction was called" was thrown, throw an Error :)
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 3 of 3 (1 FAILED) (0.019 secs / 0.007 secs)
TOTAL: 1 FAILED, 2 SUCCESS
1) callThrowFunction
test lib
the string "throwFunction was called" was thrown, throw an Error :)