Jasmine - 监视EXTJS侦听器中调用的函数

时间:2015-11-12 14:02:10

标签: javascript unit-testing extjs jasmine

我想要实现的是测试,如果单击按钮激发正确的功能。 我会给你一些代码来看看:

控制器:

init: function() {
        this.control({
            'locationSettingsWest #buttonAddLocation' : {
                click: this.settings.addLocation
            }
        });
},
settings: {
    addLocation: function() {
            console.log('addLocation called. scope below should be controller');
            console.log(this);
        }
}

最后的测试:

// code1
it('Location add button clicked, addLocation called', function() {
            console.log(tmpObj.controller); // controller declared, fine
            var scope = tmpObj.controller,
                spy = spyOn(scope.settings, 'addLocation').and.callThrough();
            tmpObj.contentWest.down('#buttonAddLocation').fireEvent('click'); // button clicked, log 'addLocation called' shows in console (dunno why twice, but shows)
            expect(spy).toHaveBeenCalled()
        });

结果是失败,茉莉说Expected spy addLocation to have been called. 当我直接调用该函数时,如下所示,它可以正常工作

// code2
it('Location add button clicked, addLocation called', function() {
            console.log(tmpObj.controller); // controller declared, fine
            var scope = tmpObj.controller,
                spy = spyOn(scope.settings, 'addLocation').and.callThrough();
            scope.settings.addLocation.call(tmpObj.controller);
            //tmpObj.contentWest.down('#buttonAddLocation').fireEvent('click'); // button clicked, log 'addLocation called' shows in console (dunno why twice, but shows)
            expect(spy).toHaveBeenCalled()
        });

所以,我想要实现的是测试,如果点击一个按钮激发一个正确的功能。

我也尝试过:

// doing a call with scope on fireEvent
tmpObj.contentWest.down('#buttonAddLocation').fireEvent.call(scope, 'click');

// spying without .and.callThrough() (which I discovered later)
spyOn(scope.settings, 'addLocation')

// looking for calls history in ...addLocation.calls ...
console.log(scope.settings.addLocation.calls);
console.log(scope.settings.addLocation.calls.any());
// ... which worked with code2 but not with code1

// and many other combinations...

谢谢!

茉莉花2.3.4 extjs 4.2.1

1 个答案:

答案 0 :(得分:1)

您需要在初始化Controller并解析处理程序引用之前调用spyOn():

describe("click tests", function() {
    var controller;

    beforeEach(function() {
        controller = new My.app.Controller(...);

        for (var fn in controller.settings) {
            spyOn(controller.settings, fn).and.callThrough();
        }

        controller.init();
    });

    it("should do something on click", function() {
        ...
    });
});