我不知道如何让 Jasmine 检查我的测试函数中的函数是否被调用。我知道我必须使用 spy ,但我显然不了解 spy 的实现,因为它目前无法正常工作。
我的函数看起来像这样:
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();
});
});
});
最佳答案
你的 spy 不太正确。
spyOn(_writeToStore, 'rootScope.store.templates.save');
应该是:
spyOn(rootScope.store.templates, 'save');
即第一个参数是函数所在的对象,第二个是函数名。
接下来的问题是要引用根作用域
关于javascript - 使用 Jasmine spies 测试函数的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28495406/