javascript - 如何测试对 eventSpy 的期望

标签 javascript backbone.js jasmine sinon

我正在尝试在保存时测试 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));

asddas

最佳答案

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/

相关文章:

javascript - 为什么 require 和 fs.existSsync 使用不同的相对路径

javascript - backbone remove view 删除 el

javascript - 使用 Jasmine 进行数据库集成测试

angularjs - 如何使用 VSCode 工具调试 jasmine karma 测试

jestjs - Jasmine.createSpy 相当于 Jest

javascript - 我如何将条件语句放入此 JavaScript 中?

javascript - Maths Capture 需要添加到同一 html 页面上的两个选项卡?

javascript - Backbone.js 使用查询字符串进行搜索

testing - 如何在守夜人测试中绕过recaptcha人工检查?

javascript - 移动设备 - iOS - Safari - window.outerHeight 返回 0