我在名为options.js
的文件中包含以下代码。我需要使用Jasmine来模拟它。我需要测试在调用chrome.storage.local.set
函数时是否调用save
。
在spec文件中,我有以下代码。但它不会调用options.js
文件中的chrome函数。有人可以指出错误吗?
beforeEach(function() {
ctrl = new OptionCtrl(scope);
chrome: {
storage: {
local: {
set: function() {
}
}
}
}
});
it('should call storage on save', function() {
spyOn(chrome.storage.local, 'set').and.callThrough();
ctrl.save({data: 'check'}, 'check');
expect(chrome.storage.local.set).toHaveBeenCalled();
});
更新1 :保存功能实施
save(data, successMessage) {
chrome.storage.local.set(data, (error) => {
if (error) {
this.status('Error Occurred. Please refresh.', 1000, 100, 'danger');
} else {
this.status(successMessage, 1000, 100, 'success');
}
});
}
Link to the options.js file - 行:122
答案 0 :(得分:1)
茉莉花的收藏很简单:
var chrome = {
storage: {
local: {
set: function() {}
}
}
}
function OptionCtrl() {
this.save = function(data, callbackStr) {
chrome.storage.local.set(data)
}
}
describe('OptionCtrl', function() {
var ctrl;
beforeEach(function() {
ctrl = new OptionCtrl({});
});
it('calls storage on save', function() {
spyOn(chrome.storage.local, 'set').and.callThrough();
var dataStub = {
data: 'check'
}
ctrl.save(dataStub, 'check');
expect(chrome.storage.local.set).toHaveBeenCalledWith(dataStub);
});
})
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>