使用 Jasmine spies 测试函数的调用

Using Jasmine spies to test the calling of functions

我不知道如何让 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();
        });
    });
});

你这个间谍不太正确。

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

应该是:

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

即第一个参数是函数所在的对象,第二个是函数名

接下来的问题是要引用根范围