Skip to content

fix: wxt unit testing plugin #1844

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

marcellino-ornelas
Copy link

@marcellino-ornelas marcellino-ornelas commented Aug 13, 2025

Overview

context: https://discord.com/channels/1212416027611365476/1404626135291003021/1404626135291003021

Currently there is a issue with WXT and unit testing with jsdom and happy-dom. When trying to run unit tests in each of the DOM environments you end up with the following errors

jsdom

Error: Invariant violation: "new TextEncoder().encode("") instanceof Uint8Array" is incorrectly false
│ 
│ This indicates that your JavaScript environment is broken. You cannot use
│ esbuild in this environment because esbuild relies on this invariant. This
│ is not a problem with esbuild. You need to fix your environment instead.
│ 
│  ❯ Object.<anonymous> ../../node_modules/esbuild/lib/main.js:201:9
│     199| }
│     200| if (!(encodeUTF8("") instanceof Uint8Array))
│     201|   throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
|         ^
│     202| 
│     203| This indicates that your JavaScript environment is broken. You cannot use

happy-dom

TypeError: The URL must be of scheme file
│  ❯ ../../node_modules/wxt/node_modules/vite/dist/node/constants.js:6:3
│       4| 
│       5| const { version } = JSON.parse(
│       6|   readFileSync(new URL("../../package.json", import.meta.url)).toString()
│        |   ^
│       7| );
│       8| const ROLLUP_HOOKS = [
│  ❯ ../../node_modules/wxt/node_modules/vite/dist/node/chunks/dep-DBxKXgDP.js:12:1

Issue

The issue is that the wxt/testing module is importing both the vitest plugin and the fake browser. So when importing the fake browser in a unit test, its importing the vitest plugin as well which is causing these errors to happen because vitest plugin is relying in packages that don't fit the jsdom environment

Fix

The fix for this to to allow importing the sub modules by themselves to prevent this conflict of interest. Now you can import just the fake browser without importing any vitest plugin code which eliminates the error

Manual Testing

Current code

// package.json
"wxt": "^0.20.7"
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import { WxtVitest } from 'wxt/testing';

export default defineConfig({
    plugins: [WxtVitest()],
    test: {
        mockReset: true,
        environment: 'jsdom',
        setupFiles: './test/setup.ts',
        globals: true,
    },
});
// mytest.test.tsx
import { describe, it, expect, beforeEach } from 'vitest';
import { fakeBrowser } from 'wxt/testing/fake-browser';
import { render, screen } from '@testing-library/react';

describe('mytest', () => {
    beforeEach(() => {
        // See https://webext-core.aklinker1.io/fake-browser/reseting-state
        fakeBrowser.reset();
    });

    it('should be able to render', async () => {
        render(<div>mytest</div>);

        expect(screen.getByText('mytest')).toBeInTheDocument();
    });
});

produces:

Error: Invariant violation: "new TextEncoder().encode("") instanceof Uint8Array" is incorrectly false
│ 
│ This indicates that your JavaScript environment is broken. You cannot use
│ esbuild in this environment because esbuild relies on this invariant. This
│ is not a problem with esbuild. You need to fix your environment instead.
│ 
│  ❯ Object.<anonymous> ../../node_modules/esbuild/lib/main.js:201:9

Fix

// package.json
"wxt": "https://pkg.pr.new/wxt@1844"
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import { WxtVitest } from 'wxt/testing/wxt-vitest-plugin';

export default defineConfig({
    plugins: [WxtVitest()],
    test: {
        mockReset: true,
        environment: 'jsdom',
        setupFiles: './test/setup.ts',
        globals: true,
    },
});
// mytest.test.tsx
import { describe, it, expect, beforeEach } from 'vitest';
import { fakeBrowser } from 'wxt/testing/fake-browser';
import { render, screen } from '@testing-library/react';

describe('mytest', () => {
    beforeEach(() => {
        // See https://webext-core.aklinker1.io/fake-browser/reseting-state
        fakeBrowser.reset();
    });

    it('should be able to render', async () => {
        render(<div>mytest</div>);

        expect(screen.getByText('mytest')).toBeInTheDocument();
    });
});
│  ✓ src/entrypoints/mytest/elements/mytest.test.tsx (1 test) 27ms
│    ✓ MyTest > should be able to render 25ms
│ 
│  Test Files  1 passed (1)
│       Tests  1 passed (1)
│    Start at  12:33:48
│    Duration  1.43s (transform 67ms, setup 130ms, collect 117ms, tests 27ms, environment 599ms, prepare 224ms)

Related Issue

This PR closes #1575

Copy link

netlify bot commented Aug 13, 2025

Deploy Preview for creative-fairy-df92c4 ready!

Name Link
🔨 Latest commit 397492c
🔍 Latest deploy log https://app.netlify.com/projects/creative-fairy-df92c4/deploys/689f8e1fc0bb370008302b37
😎 Deploy Preview https://deploy-preview-1844--creative-fairy-df92c4.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@marcellino-ornelas marcellino-ornelas changed the title Add specific imports to testing sub files Fix WXT unit testing plugin Aug 13, 2025
Copy link

codecov bot commented Aug 13, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.08%. Comparing base (9d4724f) to head (a3db7a9).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1844      +/-   ##
==========================================
+ Coverage   80.97%   81.08%   +0.11%     
==========================================
  Files         131      131              
  Lines        6679     6679              
  Branches     1092     1093       +1     
==========================================
+ Hits         5408     5416       +8     
+ Misses       1260     1252       -8     
  Partials       11       11              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

pkg-pr-new bot commented Aug 13, 2025

Open in StackBlitz

@wxt-dev/analytics

npm i https://pkg.pr.new/@wxt-dev/analytics@1844

@wxt-dev/auto-icons

npm i https://pkg.pr.new/@wxt-dev/auto-icons@1844

@wxt-dev/browser

npm i https://pkg.pr.new/@wxt-dev/browser@1844

@wxt-dev/i18n

npm i https://pkg.pr.new/@wxt-dev/i18n@1844

@wxt-dev/module-react

npm i https://pkg.pr.new/@wxt-dev/module-react@1844

@wxt-dev/module-solid

npm i https://pkg.pr.new/@wxt-dev/module-solid@1844

@wxt-dev/module-svelte

npm i https://pkg.pr.new/@wxt-dev/module-svelte@1844

@wxt-dev/module-vue

npm i https://pkg.pr.new/@wxt-dev/module-vue@1844

@wxt-dev/runner

npm i https://pkg.pr.new/@wxt-dev/runner@1844

@wxt-dev/storage

npm i https://pkg.pr.new/@wxt-dev/storage@1844

@wxt-dev/unocss

npm i https://pkg.pr.new/@wxt-dev/unocss@1844

@wxt-dev/webextension-polyfill

npm i https://pkg.pr.new/@wxt-dev/webextension-polyfill@1844

wxt

npm i https://pkg.pr.new/wxt@1844

commit: a3db7a9

@marcellino-ornelas marcellino-ornelas changed the title Fix WXT unit testing plugin fix: wxt unit testing plugin Aug 15, 2025
@marcellino-ornelas marcellino-ornelas marked this pull request as ready for review August 15, 2025 19:40
@@ -183,6 +183,14 @@
"types": "./dist/testing/index.d.ts",
"default": "./dist/testing/index.mjs"
},
"./testing/fake-browser": {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optionally we could remove the import above so no one can import wxt/testing directly 🤔

"types": "./dist/testing/fake-browser.d.ts",
"default": "./dist/testing/fake-browser.mjs"
},
"./testing/wxt-vitest-plugin": {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I opted to follow the same testing convention of wxt/testing/wxt-vitest-plugin

we can definitely change this to wxt/wxt-vitest-plugin if ya'll like that better 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

The jsdom environment throws an error when using the WxtVitest plugin in vitest
1 participant