sinon - stub method of private variable

时间:2015-10-29 15:52:38

标签: backbone.js sinon chai

I have been tasked with writing the tests for the following Backbone view. However I did not write the code.

In the following code example I want to stub/spy the update method so that I can check the function is called when the liked attribute of the view's model is changed, but I seem to not be able to target the method.

Is it possible to stub the update function at all?

When I run my tests it logs Hello but the test return the following error: 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);
}

I have tried to stub the update function in the beforeEach function for the tests:

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

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

In my test suite:

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;

    });

1 个答案:

答案 0 :(得分: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);