我正在使用 Jasmine 为我的 Backbone 缓存编写单元测试,并尝试使用 Sinon.js 模拟函数响应。对于不同的测试,我希望会发生不同的事情,所以我在每个测试之前创建一个模拟并在之后删除它,然后在expects
测试本身中填充行为。但是,我遇到了一个错误并且测试失败了。
这是我的规范,仅包含相关测试(其他测试不使用模拟):
describe("mysite.core.Cache.XFooInfo", function() {
var fnMock;
beforeEach(function() {
fnMock = sinon.mock(fn);
});
afterEach(function() {
delete fnMock;
});
it("should make a request after function fooCreated called", function() {
fnMock.expects("sendRequest").once().withExactArgs("ModuleFoo", "getFoo", ["1000"]);
events.trigger("fooCreated", [{Args:[test.data.XFooInfo]}]);
fnMock.verify();
});
});
describe("mysite.core.Cache.XFooBarInfo", function() {
var fnMock;
beforeEach(function() {
fnMock = sinon.mock(fn);
});
afterEach(function() {
delete fnMock;
});
it("should make a request after function booUpdated called", function() {
var booCopy = $.extend(true, {}, test.data.XBooInfo);
booCopy[0].Args[0].FooID = "12345";
fnMock.expects("sendRequest").once().withExactArgs("ModuleFoo", "getFoo", ["12345"]);
events.trigger("booUpdated", booCopy);
fnMock.verify();
});
});
第一个测试工作正常并通过。然而,第二个测试给了我这个错误:
TypeError: Attempted to wrap sendRequest which is already wrapped
at Object.wrapMethod (https://localhost:8443/mysite/web/tests/libs/sinon-1.7.1.js:528:23)
at Object.expects (https://localhost:8443/mysite/web/tests/libs/sinon-1.7.1.js:2092:27)
at null.<anonymous> (https://localhost:8443/mysite/web/shasta-cList-tests/spec/CacheSpec.js:909:15)
at jasmine.Block.execute (https://localhost:8443/mysite/web/tests/libs/jasmine-1.2.0.rc3/jasmine.js:1024:15)
at jasmine.Queue.next_ (https://localhost:8443/mysite/web/tests/libs/jasmine-1.2.0.rc3/jasmine.js:2025:31)
at jasmine.Queue.start (https://localhost:8443/mysite/web/tests/libs/jasmine-1.2.0.rc3/jasmine.js:1978:8)
at jasmine.Spec.execute (https://localhost:8443/mysite/web/tests/libs/jasmine-1.2.0.rc3/jasmine.js:2305:14)
at jasmine.Queue.next_ (https://localhost:8443/mysite/web/tests/libs/jasmine-1.2.0.rc3/jasmine.js:2025:31)
at jasmine.Queue.start (https://localhost:8443/mysite/web/tests/libs/jasmine-1.2.0.rc3/jasmine.js:1978:8)
at jasmine.Suite.execute (https://localhost:8443/mysite/web/tests/libs/jasmine-1.2.0.rc3/jasmine.js:2450:14)
我在 Sinon.js 文档中找不到任何东西来告诉我我做错了什么。我知道它verify
也restore
对它模拟的所有函数做了 a ,我认为这足以让我expects
为同一个函数编写一个新的行为,但显然我错了。
这样做的正确方法是什么?