1

I am trying to test a backbone.model when saving.
Here's my piece of code.
As you can see from the comment there is a problem with toHaveBeenCalledOnce method.

P.S.:
I am using jasmine 1.2.0 and 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(expect(this.eventSpy));

asddas

4

3 回答 3

2

茉莉没有任何作用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');

更新

你现在得到的错误,“期望一个间谍,但得到了功能”正是因为这个。您正在使用 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);

你和茉莉一起使用诗乃的理由是什么?我推荐第一个解决方案,因为那时 Jasmine 将在测试失败时显示更多信息。

于 2012-06-01T16:09:28.120 回答
1

有一个名为jasmine-sinon的库,它为 jasmine添加了特定于 sinon 的匹配器。

它允许您执行以下操作

expect(mySpy).toHaveBeenCalledOnce();
expect(mySpy).toHaveBeenCalledBefore(myOtherSpy);
expect(mySpy).toHaveBeenCalledWith('arg1', 'arg2', 'arg3');
于 2012-06-02T02:41:49.360 回答
1

尝试使用toHaveBeenCalledTimes方法:

expect(this.eventSpy).toHaveBeenCalledTimes(1);
于 2021-02-15T11:24:28.407 回答