问题
I'm a very beginner with testing and started using jest. This function I have saves data in chrome.storage.local and I want to test if chrome.storage.local called 3 times. Here is the function:
saveData: function(){
chrome.storage.local.set({'blackList': bgModule.blackList}, function() {});
chrome.storage.local.set({'pastDays': bgModule.pastDays}, function() {});
chrome.storage.local.set({'websiteList': bgModule.websiteList}, function() {});
}
and here is my test:
const bgModule = require("../../app/Background/background.js");
const chrome = {
storage: {
local: {
set: function() {},
get: function() {}
}
}
};
let blackListStub = bgModule.blackList;
let pastDaysStub = [
{day: "day1"},
{day2: "day2"},
{day3: "day3"}];
let websiteListStub = [
{websiteName: "facebook.com"},
{websiteName: "stackoverflow.com"},
{websiteName: "github.com"}];
it ("should save data in local storage", () => {
spyOn(bgModule, 'saveData');
bgModule.saveData();
const spy = spyOn(chrome.storage.local, 'set');
spy({'blackList' : blackListStub});
spy({'pastDays' : pastDaysStub});
spy({'websiteList' : websiteListStub});
expect(spy).toHaveBeenCalledWith({'blackList' : blackListStub});
expect(spy).toHaveBeenCalledWith({'pastDays' : pastDaysStub});
expect(spy).toHaveBeenCalledWith({'websiteList' : websiteListStub});
expect(bgModule.saveData).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledTimes(3);
});
Test passes but it's incorrect. I want to make it work so when I change saveData it will break the test. The test I have has everything hardcoded into it and doesn't depend on saveData at all. I looked for example and tutorial materials and couldn't find anything for this case. Any help or direction I should take would be very helpful.
After help and correct answer with use of global.chrome refactored test looks like this:
it ("should save data in local storage", () => {
bgModule.saveData();
expect(chrome.storage.local.set).toHaveBeenCalledTimes(3);
});
回答1:
The easiest thing would be to use dependency injection, so instead of calling chrome.storage.local
directly, passed it as an argument to your function that then can be easily replaced by a mock in your test.
The other way would be to add it as a global variable into your test environment like this:
const get = jest.fn()
const set = jest.fn()
global.chrome = {
storage: {
local: {
set,
get
}
}
来源:https://stackoverflow.com/questions/48894790/testing-chrome-storage-local-set-with-jest