svelte: `SvelteSet` does not behave correctly in Vitest

Describe the bug

The following test fails.

import { SvelteSet } from "svelte/reactivity";
import { expect, test } from "vitest";

class Group {
	selected = new SvelteSet<string>();
}

class Item {
	group: Group;
	id: string;

	constructor(group: Group, id: string) {
		this.group = group;
		this.id = id;
	}

	#selected = $derived.by(() => this.group.selected.has(this.id));

	get selected() {
		return this.#selected;
	}

	set selected(value: boolean) {
		if (value) {
			this.group.selected.add(this.id);
		} else {
			this.group.selected.delete(this.id);
		}
	}
}

test("Item.selected", () => {
	const cleanup = $effect.root(() => {
		const group = new Group();
		const item = new Item(group, "foo");

		expect(group.selected.has("foo")).toBe(false);
		expect(item.selected).toBe(false);

		item.selected = true;
		expect(group.selected.has("foo")).toBe(true);	// this is fine
		expect(item.selected).toBe(true);		// but this throws an error

		item.selected = false;
		expect(group.selected.has("foo")).toBe(false);
		expect(item.selected).toBe(false);
	});

	cleanup();
});

This issue only happens in Vitest. If you run the reproduction provided below, you will find that the same code works fine in the browser. Both values are the same, as expected.

Reproduction

https://github.com/abdel-17/svelte-vitest-set-bug-repro

Logs

No response

System Info

System:
    OS: macOS 15.0.1
    CPU: (8) x64 Intel(R) Core(TM) i5-1038NG7 CPU @ 2.00GHz
    Memory: 3.80 GB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 22.9.0 - /usr/local/bin/node
    Yarn: 1.22.22 - /usr/local/bin/yarn
    npm: 10.8.3 - /usr/local/bin/npm
    pnpm: 9.12.0 - /usr/local/bin/pnpm
    bun: 1.1.31 - /usr/local/bin/bun
  Browsers:
    Safari: 18.0.1

Severity

annoyance

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 33 (27 by maintainers)

Commits related to this issue

Most upvoted comments

to be clear you don’t need a JSDOM environment, you need a browser environment.

None of this makes sense, unless vite is doing some module isolation logic that means that the runtime and the tests aren’t connected. Like I said, I have no computer till Monday 😕

Yeah it likely won’t make a difference. I’ll take a look into this on Monday 😃 I’m away without my laptop this weekend