How to use vitest for testing Chrome Extensions? #3090
Replies: 2 comments
-
No replies? I'm going crazy writing tests for a Chrome Extension after a migration to Vite/vitest, it's unbelievable how careless this library is. The only test framework working with Vite and no whatsoever support or communication or enough documentation. I'm really disappointed |
Beta Was this translation helpful? Give feedback.
-
Maybe it will help someone. In my extension reddit-post-notifier I used webextension-polyfill so that the extension works in both Firefox and Chrome. Additionally, this library is easy to mock. vitest.config.ts: export default defineConfig({
test: {
environment: 'jsdom',
setupFiles: r('./src/test-utils/setup-tests.ts'),
},
}); setup-test.ts import { vi } from 'vitest';
import 'vitest-dom/extend-expect';
// without chrome.runtime.id webextension-polyfill won't work
const chromeObject = { runtime: { id: 'some-test-id' } };
(globalThis as any).chrome = chromeObject;
vi.mock('webextension-polyfill'); Example of mocking describe('count unread', () => {
const storageData = {
// ...
}
const total = 3
it('should count unread items', async () => {
vi.spyOn(storage, 'getAllData').mockImplementation(async () => storageData);
vi.mocked(browser.action.setBadgeText).mockImplementationOnce(async (value) => {
expect(value.text).toBe(total.toString());
});
await expect(storage.countNumberOfUnreadItems()).resolves.toBe(total);
expect(browser.action.setBadgeText).toHaveBeenCalled();
vi.mocked(storage.getAllData);
});
}); |
Beta Was this translation helpful? Give feedback.
-
Hi all, apologies if this is a stupid question.
qq: What is the best way to use vitest to test Chrome Extensions?
Is there something like jest-chrome that gives access to the Chrome APIs (such as chrome.runtime), for example?
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions