Setting `window.innerWidth` doesn't actually set `innerWidth` on happy-dom's `window` object
Describe the bug
I was having unexpected test failures in some of my tests ran in happy-dom environment related to window.matchMedia(), after digging a bit and adding a few console.log statements in node_modules/happy-dom/ I discovered that the modifications to window.innerWidth in my tests were not reflected on the window object the window methods like matchMedia() were bound to. Here is the minimal reproduction to demonstrate the issue:
test('window.matchMedia()', () => {
window.innerWidth = 100;
expect(window.matchMedia('(max-width: 100px)').matches).toBe(true);
});
adding the following at the top of this test file fixes the issue:
import { Window } from 'happy-dom';
const window = new Window();
But obviously it would be desirable to not have to do this in every test file and not have to explain that it's only done due to a bug in comments.
Reproduction
https://stackblitz.com/edit/vitest-dev-vitest-xs8z4w5n?file=test%2Fbasic.test.ts
System Info
System:
OS: Linux 7.0 EndeavourOS
Container: Yes
Shell: 5.3.9 - /bin/bash
Binaries:
Node: 26.1.0 - /run/user/1000/fnm_multishells/135812_1778693298144/bin/node
npm: 11.13.0 - /run/user/1000/fnm_multishells/135812_1778693298144/bin/npm
Browsers:
Chromium: 148.0.7778.167
Firefox: 150.0.2
Firefox Developer Edition: 150.0.2
npmPackages:
vitest: ^4.1.6 => 4.1.6
Used Package Manager
npm
Validations
- [x] Follow our Code of Conduct
- [x] Read the Contributing Guidelines.
- [x] Read the docs.
- [x] Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- [x] Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- [x] The provided reproduction is a minimal reproducible example of the bug.
From the rough reading, it looks to me that Vitest intentionally doesn’t write every window assignment through to the underlying happy-dom/jsdom Window; it keeps a facade so window, self, global, and globalThis share state consistently.
https://github.com/vitest-dev/vitest/blob/d3c964bfcb5a47840e892e7ff4b1146dd4ca8b6d/packages/vitest/src/integrations/env/utils.ts#L69-L83
The obvious "fix" would be write through win[key] = value, but this would be likely too breaking change since some direct assignment such as window.document = ... or window.location = ... seems to cause hard errors, which is currently allowed since it just swaps out as global getter/setter level.
That said, happy-dom making assigned innerWidth visible to matchMedia() seems like useful behavior for Vitest to preserve even though in real window window.innerWidth isn't even writable. A reasonable Vitest-side direction could be a small explicit allowlist of mutable window state, e.g. viewport-related properties, that should write through to the backing DOM window.
While playing around with some, it might not be that breaking to always assign window[key] = ....