Skip to content
Advertisement

Testing Cross Browser Extension With Jest, How To Mock Chrome Storage API?

After putting off testing for a while now due to Cypress not allowing visiting chrome:// urls, I decided to finally understand how to unit/integration test my extension – TabMerger. This comes after the many times that I had to manually test the ever growing functionality and in some cases forgot to check a thing or two. Having automated testing will certainly speed up the process and help me be more at peace when adding new functionality.

To do this, I chose Jest since my extension was made with React (CRA). I also used React Testing Library (@testing-library/react) to render all React components for testing.

As I recently made TabMerger open source, the full testing script can be found here

Here is the test case that I want to focus on for this question:

JavaScript

I mocked the Chrome API according to my needs, but feel that something is missing. To mock the Chrome API I followed this post (along with many others, even for other test runners like Jasmine): testing chrome.storage.local.set with jest.

Even though the Chrome storage API is mocked, I think the issue lies in this function which gets called upon initial render. That is, I think the chrome.storage.local.get is not actually being executed, but am not sure why.

JavaScript

The reason I think the mocked Chrome storage API is not working properly is because when I manually set it in my tests, the number of tabs does not increase from 0. Which forced me to pass a prop (props.init_tabs) to my Tab component for testing purposes (https://github.com/lbragile/TabMerger/blob/f78a2694786d11e8270454521f92e679d182b577/src/Tab/Tab.js#L33-L35) – something I want to avoid if possible via setting local storage.

Can someone point me in the right direction? I would like to avoid using libraries like jest-chrome since they abstract too much and make it harder for me to understand what is going on in my tests.

Advertisement

Answer

I think I have a solution for this now, so I will share with others.

I made proper mocks for my chrome storage API to use localStorage:

JavaScript

Also, to simulate the tab settings on initial render, I have a beforeEach hook which sets my localStorage using the above mock:

JavaScript

AND most importantly, when I render(<Tab/>), I noticed that I wasn’t supplying the id prop which caused nothing to render (in terms of tabs from localStorage), so now I have this:

JavaScript

Which passes!!

current testing state

Now on to drag and drop testing 😊

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement