I am developing Chrome App with AngularJS. As my app uses chrome.storage I wrote wrapper:
angular.module('myApp').factory('chromeStorageApi', function($window){
if(typeof $window.chrome.storage == 'undefined')
return false;
return{
set:function(obj, callback){
$window.chrome.storage.local.set(obj, callback)
return true;
},
.............................
}
}
I have violated TDD methodology and now I want to test my wrapper. But all my attempts were not successful. I tried to check that, for example, $window.chrome.storage.local.set() has the same arguments as chromeStorageApi.set() but I could not find a way how I can mock $window.chrome.storage.local.
UPDATED:
My last version of Unit test:
describe('chromeStorageApi', function(){
beforeEach(module('myApp'));
it('should be able to set data to the storage', inject(function(chromeStorageApi, $window){
spyOn($window.chrome.storage.local, 'set')
chromeStorageApi.set({'key':'value'}, function(){ }());
expect($window.chrome.storage.local.set).toHaveBeenCalled();
expect($window.chrome.storage.local.set).toHaveBeenCalledWith({'key':'value'}, function(){ }());
}));
});
But I get an error:
TypeError: 'undefined' is not an object (evaluating '$window.chrome.storage')
I made working tests for me. Here there are:
describe('chromeStorageApi', function(){
var mockWindow, chromeStorageApi;
beforeEach(module('myApp'));
beforeEach(function(){
mockWindow = {
chrome:{
storage:{
local: sinon.stub({
set: function(){ },
get: function(){ },
remove: function(){ },
clear: function(){ }
})
}
},
addEventListener: function(){ }
}
module(function($provide){
$provide.value('$window', mockWindow);
})
})
beforeEach(inject(function(_chromeStorageApi_){
chromeStorageApi =_chromeStorageApi_;
}))
it('should be able to set data to the storage', function(){
chromeStorageApi.set({'key':'value'}, function(){ }());
expect(mockWindow.chrome.storage.local.set).toHaveBeenCalled();
expect(mockWindow.chrome.storage.local.set).toHaveBeenCalledWith({'key':'value'}, function(){ }());
});
it('should be able to get data from the storage', function(){
chromeStorageApi.get('key', function(){ });
expect(mockWindow.chrome.storage.local.get).toHaveBeenCalled();
expect(mockWindow.chrome.storage.local.get).toHaveBeenCalledWith('key');
})
})
I am using sinonJS to create stub with methods. I hope it will be helpful for someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With