【问题标题】:Using Jasmine spies to test the calling of functions使用 Jasmine spies 测试函数的调用
【发布时间】:2015-02-13 08:34:14
【问题描述】:

我不知道如何让 Jasmine 检查我的测试函数中的函数是否被调用。我知道我必须使用间谍,但我显然不了解间谍的实现,因为它目前不起作用。

我的函数看起来像这样:

function templates($rootScope, ShareStats) {
    return {
        _writeToStore: function(tmpl, tmplOld) {
            $rootScope.store.templates.save(tmpl);
            if (tmplOld) {
                ShareStats.update(tmpl, tmplOld);
            } else {
                ShareStats.saveAll();
            }
        },
    }
}

我的测试是这样的:

describe('Unit: templates', function() {
    var Templates,
        rootScope,
        tmplOld = {...},
        tmplNew = {...};

    beforeEach(function() {
        module('myApp');
        inject(function($injector) {...});
    });

    describe('Templates._writeToStore', function() {
        it('should save object to $rootScope.store.templates', function() {
            var _writeToStore = Templates._writeToStore(tmplNew, tmplOld);
            spyOn(_writeToStore, 'rootScope.store.templates.save');
            _writeToStore(tmplNew, tmplOld);
            expect(rootScope.store.templates.save).toHaveBeenCalled();
        });
        it('should call ShareStats.update() if tmplOld is passed', function() {
            var _writeToStore = Templates._writeToStore(tmplNew, tmplOld);
            spyOn(_writeToStore, 'ShareStats.update');
            _writeToStore(tmplNew, tmplOld);
            expect(ShareStats.update).toHaveBeenCalled();
        });
    });
});

【问题讨论】:

    标签: javascript unit-testing testing jasmine


    【解决方案1】:

    你的间谍不太正确。

    spyOn(_writeToStore, 'rootScope.store.templates.save');
    

    应该是:

    spyOn(rootScope.store.templates, 'save');
    

    即函数所在的对象作为第一个参数,函数名作为第二个参数。

    那么问题就是要引用根作用域

    【讨论】:

    • rootScope是通过injector函数注入的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    相关资源
    最近更新 更多