From 3f7187d75ad0cbf557b6d5484e367dac83670854 Mon Sep 17 00:00:00 2001 From: Aaron Klinker Date: Mon, 30 Oct 2023 09:31:50 -0500 Subject: [PATCH] docs(fake-browser): Update vitest setup --- docs/guide/fake-browser/testing-frameworks.md | 58 ++++++++++++------- 1 file changed, 36 insertions(+), 22 deletions(-) diff --git a/docs/guide/fake-browser/testing-frameworks.md b/docs/guide/fake-browser/testing-frameworks.md index 1f84497..8199f7a 100644 --- a/docs/guide/fake-browser/testing-frameworks.md +++ b/docs/guide/fake-browser/testing-frameworks.md @@ -15,7 +15,42 @@ To tell Vitest to use `@webext-core/fake-browser` instead of `webextension-polyf export { fakeBrowser as default } from '@webext-core/fake-browser'; ``` -Then write your tests. Make sure to call `vi.mock("webextension-polyfill")` to tell vitest to use the mock we just setup. +Next, create a global setup file, `vitest.setup.ts`, where we actually test vitest to use our mock: + +```ts +import { vi } from 'vitest'; + +vi.mock('webextension-polyfill'); +``` + +Finally, update your `vitest.config.ts` file: + +```ts +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + // List setup file + setupFiles: ['vitest.setup.ts'], + + // List ALL dependencies that use `webextension-polyfill` under `server.deps.include`. + // Without this, Vitest can't mock `webextension-polyfill` inside the dependencies, and the + // actual polyfill will be loaded in tests + // + // You can get a list of dependencies using your package manager: + // - npm list webextension-polyfill + // - yarn list webextension-polyfill + // - pnpm why webextension-polyfill + server: { + deps: { + include: ['@webext-core/storage', ...], + }, + }, + }, +}); +``` + +Then write your tests! ```ts import browser from 'webextension-polyfill'; @@ -28,9 +63,6 @@ function isXyzEnabled(): Promise { return localExtStorage.getItem('xyz'); } -// Enable the global mock -vi.mock('webextension-polyfill'); - describe('isXyzEnabled', () => { beforeEach(() => { // Reset the in-memory state before every test @@ -49,24 +81,6 @@ describe('isXyzEnabled', () => { }); ``` -Calling `vi.mock` in every file is a pain. Instead, you can add a setup file that calls it before all your tests: - -```ts -// vitest.setup.ts -vi.mock('webextension-polyfill'); -``` - -```ts -// vitest.config.ts -import { defineConfig } from 'vitest/config'; - -export default defineConfig({ - testing: { - setupFiles: ['vitest.setup.ts'], - }, -}); -``` - ## Jest To tell Jest to use `@webext-core/fake-browser` instead of `webextension-polyfill`, you need to setup a global mock: