Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock chrome APIs using JEST framework?

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>)
like image 700
HarshaVardhanReddy Bommareddy Avatar asked Oct 29 '22 08:10

HarshaVardhanReddy Bommareddy


1 Answers

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.

like image 132
Yuri Drabik Avatar answered Nov 09 '22 11:11

Yuri Drabik