【问题标题】:How do I specify a Sinon.JS spy function as part of a class definition?如何将 Sinon.JS 间谍函数指定为类定义的一部分?
【发布时间】:2013-01-30 05:15:39
【问题描述】:

我正在使用 Require.js 和 Backbone.Marionette 编写一个 Backbone.js 应用程序,并使用带有 Chai、Sinon 和 Sinon-Chai 的 Mocha 对其进行测试。我一直使用Jarrod Overson's Backbone Marionette with Require.JS TODO sample 作为应用程序结构的参考,Jim Newbery's posts on testing Backbone apps 作为单元测试的参考。

我的问题是尝试测试将Marionette ItemView 添加到Marionette Application object。我认为测试是否添加了 ItemView 的最佳方法是观察其 render() 方法是否被调用。由于 Marionette 提供了默认的 render() 实现,我认为最好只使用 Sinon spy 进行 onRender() 回调。

我使用Squire.JS 为我的 ItemView 返回一个存根类,如下所示:

define(['Squire', 'backbone.marionette'], function(Squire, Marionette) {
    describe('App', function() {

        var testContext;

        beforeEach(function(done) {
            testContext = {};

            testContext.injector = new Squire();

            testContext.renderSpy = sinon.spy();

            testContext.injector.mock('app/views/Header', function() {
                var stub_template_html = "<div></div>";
                var HeaderStub = Marionette.ItemView.extend({
                    template: function(serialized_model) {
                        return _.template(stub_template_html);
                    }
                });
                return HeaderStub;
            });

            testContext.injector.require(['app/app'], function(app) {
                testContext.app = app;
                done();
            });
        });

        it ('Should add a Header view to the \'header\' region', function() {
            testContext.app.start();
            expect(testContext.renderSpy).to.be.called();
        });

当我通过 Chrome 运行 Mocha 时,我收到了预期的错误:“expected spy to have been called at least once, but it was never called.”但是,如果我将Sinon spy函数指定为onRender()回调,如下图

var HeaderStub = Marionette.ItemView.extend({
    // ...
    onRender: testContext.renderSpy
});

我收到一条错误消息,指出 called() 方法不是函数。

有没有办法在类定义中将 Sinon spy 函数指定为方法?或者,是否有更好的方法来测试此代码?我对 JavaScript 还很陌生,所以这可能是一个更普遍的问题,而不是特定于 Sinon 的问题。

感谢任何帮助。

【问题讨论】:

    标签: javascript mocha.js sinon


    【解决方案1】:

    我不确定你使用的是什么断言库,但要检查你用 sinon 监视的函数是否被调用,你必须检查 spy 的 called 属性。见http://sinonjs.org/docs/#spies

    spy.call

    如果间谍至少被调用一次则为真

    所以你的断言应该是这样的:

    expect(testContext.renderSpy).to.be(true);
    

    【讨论】:

    • 我将Chai 用于我的断言库,并使用Sinon-Chai 插件来提供一致的断言。我认为我的语法是正确的,但我会尝试一下您的建议,看看是否会有所作为。谢谢。
    • 你是对的。我使用了错误的语法。 called 是一个属性,而不是一个函数。您可以使用expect(testContext.renderSpy.called).to.be.true (native Chai) 或 expect(testContext.renderSpy).to.be.called (Sinon-Chai)。注意语句末尾没有括号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    相关资源
    最近更新 更多