vitest icon indicating copy to clipboard operation
vitest copied to clipboard

`provide`/`inject` can't serialize Set

Open jendrikw opened this issue 1 month ago • 3 comments

Describe the bug

in globalSetup, I use project.provide('set', new Set([1, 2]));.

In the test, the value returned from inject is {}. It is not an instance of Set. The following test fails:

const set = inject('set');

test('set', () => {
  expect.soft(set).toBeInstanceOf(Set); // expected {} to be an instance of Set
  expect.soft(set).toEqual(new Set([1, 2])); // expected {} to deeply equal Set{ 1, 2 }
});

Reproduction

https://github.com/jendrikw/vitest-provide-inject-bug

System Info

System:
    OS: Linux 7.2 Debian GNU/Linux forky/sid
    CPU: (16) x64 AMD Ryzen 7 PRO 5750G with Radeon Graphics
    Memory: 6.42 GB / 30.71 GB
    Container: Yes
    Shell: 5.3.15 - /bin/bash
  Binaries:
    Node: 24.21.0 - /usr/bin/node
    npm: 12.2.0 - /usr/bin/npm
  Browsers:
    Chromium: 156.0.8078.47
    Firefox: 159.0.1
    Firefox Developer Edition: 159.0.1
  npmPackages:
    @vitest/browser-playwright: ^5.1.0 => 5.1.0 
    @vitest/ui: latest => 5.1.0 
    vite: latest => 8.3.6 
    vitest: latest => 5.1.0

Used Package Manager

npm

Validations

jendrikw avatar Nov 05 '26 11:11 jendrikw

It is probably serialized and deserialized from JSON. This is in contrast to the spec which states

Properties have to be strings and values need to be serializable because this object will be transferred between different processes.

jendrikw avatar Nov 05 '26 11:11 jendrikw

I can reproduce this on main, but only in browser mode. With the same globalSetup, forks and threads pass the values through correctly (structuredClone / serialization: 'advanced'). With the Playwright provider (chromium):

provided value inject() in the browser
new Set([1, 2]) {}
new Map([['a', 1]]) {}
new Date(0) '1970-01-01T00:00:00.000Z'

The browser pool serializes the provided context with flatted's stringify (pools/browser.ts), which is JSON-based, so anything outside plain JSON gets lost. The provide docs promise structured-clone types.

nomadical avatar Nov 09 '26 09:11 nomadical

I have a fix for this: the browser pool and the tester now encode the provided context with @ungap/structured-clone/json instead of flatted (@vitest/web-worker already depends on it). Set, Map, Date, RegExp, BigInt and cyclic objects arrive intact; a BigInt used to make flatted throw. A browser spec covers each type and fails on main.

Happy to open a PR if you'd like it.

nomadical avatar Nov 16 '26 07:11 nomadical