【问题标题】:sinon - stub method of private variablesinon - 私有变量的存根方法
【发布时间】:2016-01-29 20:57:18
【问题描述】:

我的任务是为以下Backbone 视图编写测试。但是我没有写代码。

在下面的代码示例中,我想存根/监视update 方法,以便我可以检查在视图模型的liked 属性更改时调用的函数,但我似乎无法定位方法。

是否可以存根 update 函数?

当我运行测试时,它会记录 Hello 但测试返回以下错误: AssertionError: expected update to have been called at least once, but it was never called

my.Special.Class.LikeButton = function (options) {
    /* ***** Other private variables ******* */

    var LikeButton = Marionette.ItemView.extend({
        model: null,
        sSolidPoly: null,
        sEmptyPoly: null,

        events: {
            'click': 'toggleLike'
        },

        initialize: function (options) {

            //Listen to changes in like property in case it's changed from another location in the UI
            this.listenTo(this.model, 'change:liked', this.update);
        },

        onRender: function () {
            this.setElement(this.el.innerHTML);

        },

        update: function () {
            console.log('Hello');
            .....
        }
    });


    return new LikeButton(options);
}

我已尝试在 beforeEach 函数中为测试存根 update 函数:

this._view = new my.Special.Class.LikeButton({
            template: '#like-button-template',
            model: this.model
        });

        this.updateStub = sinon.stub(this._view, 'update');

在我的测试套件中:

it('change to model liked attribute calls update', function () {

        var __view = this._view.render();

        this.model.set({liked: true});

        expect(this.updateStub).has.been.called;

    });

【问题讨论】:

    标签: backbone.js sinon chai


    【解决方案1】:

    我认为这是一个测试套件暴露过于嵌套的东西的一个很好的例子。 Imo 而不是试图解决这个问题,你应该将嵌套的 LikeButton 放在一个单独的模块中,并将其导入该文件并在它自己的文件中进行测试。

    否则试试:

    var model = ...;
    var likeButton = my.Special.Class.LikeButton({ model: model });
    spyOn(likeButton, 'update');
    model.set('liked', true);
    expect(likeButton.update).toHaveBeenCalledWith(model, true);
    

    【讨论】:

    • @hyprstack 抱歉,我是用茉莉花语法写的!
    • 不用担心。我认为最好的方法是按照您的建议将它放在一个单独的模块中。另一种方法返回与我描述的相同的错误。
    猜你喜欢
    • 2017-07-12
    • 2021-02-20
    • 1970-01-01
    • 2016-01-02
    • 2021-06-10
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多