Skip to content

SvelteSet does not behave correctly in Vitest #13961

@abdel-17

Description

@abdel-17

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions