我正在尝试在保存时测试 backbone.model。
这是我的一段代码。
从评论中可以看出,toHaveBeenCalledOnce
方法存在问题。
附言:
我正在使用 jasmine 1.2.0 和 Sinon.JS 1.3.4
describe('when saving', function ()
{
beforeEach(function () {
this.server = sinon.fakeServer.create();
this.responseBody = '{"id":3,"title":"Hello","tags":["garden","weekend"]}';
this.server.respondWith(
'POST',
Routing.generate(this.apiName),
[
200, {'Content-Type': 'application/json'}, this.responseBody
]
);
this.eventSpy = sinon.spy();
});
afterEach(function() {
this.server.restore();
});
it('should not save when title is empty', function() {
this.model.bind('error', this.eventSpy);
this.model.save({'title': ''});
expect(this.eventSpy).toHaveBeenCalledOnce(); // TypeError: Object [object Object] has no method 'toHaveBeenCalledOnce'
expect(this.eventSpy).toHaveBeenCalledWith(this.model, 'cannot have an empty title');
});
});
console.log(期望(this.eventSpy));
最佳答案
Jasmine 没有函数 toHaveBeenCalledOnce
。您需要自己检查计数。
expect(this.eventSpy).toHaveBeenCalled();
expect(this.eventSpy.callCount).toBe(1);
所以我想在你的情况下,你会想要这个:
expect(this.eventSpy.callCount).toBe(1);
expect(this.eventSpy).toHaveBeenCalledWith(this.model, 'cannot have an empty title');
已更新
你现在得到的错误,“预期是 spy ,但得到了功能”正是因为这个。您正在使用 Sinon 库 Spy,并将其传递给需要 Jasmine Spy 的 Jasmine 函数。
你应该做:
this.eventSpy = jasmine.createSpy();
或
expect(this.eventSpy.calledOnce).toBe(true);
expect(this.eventSpt.calledWith(this.model, 'cannot have an empty title')).toBe(true);
您将 Sinon 与 Jasmine 一起使用的原因是什么?我推荐第一个解决方案,因为 Jasmine 将在测试失败时显示更多信息。
关于javascript - 如何测试对 eventSpy 的期望,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10852815/