Reputation: 61
I want to mock the chrome apis using jest framework.
For example I am using chrome.browserAction.setIcon
to send a message to background script. How can I mock chrome.browserAction.setIcon
or any other apis such as chrome.runtime.sendMessage
to test if the method has been called?
I have tried using jest.spyOn() for testing whether the method has been called.
Here is the test method
test("mock testing chrome",()=>{
spyOn(chrome,
chrome.browserAction.setIcon);
content.chromemocktest();
expect(spy).toHaveBeenCalledWith({path:"/images.png"});
});
And the method I am testing is :
chromemocktest: function(){
chrome.browserAction.setIcon({path:"/image.png"});
}
When I run the npm run test
for running test cases, it is throwing an error as shown below.
<spyOn> : stub() method does not exist
Usage: spyOn(<object>, <methodName>)
Upvotes: 6
Views: 4223
Reputation: 91
Take a look at the module @bumble/jest-chrome. I just used it in my TS project, works like a charm, and super easy to use.
Upvotes: 2
Reputation: 716
The problem is that the chrome object doesn't exist in the nodejs global object.
So you have to create a mock object first:
global.chrome = {
browserAction: {
setIcon: function () {}
}
};
After that you should be able to spy the object's method:
spyOn(chrome, chrome.browserAction.setIcon);
If you don't want to create mock for every object of the Chrome API by yourself you can use the following ready solution.
Upvotes: 0