在使用 jest 和 @testing-library/svelte 测试 svelte 组件时,状态在测试之间共享,每次测试后是否可以拆除,所以我有更多独立的单元测试。
商店/主题
import { writable } from "svelte/store";
export const LOCAL_STORAGE_KEY = "current:theme";
export const THEMES = {
DARK: "dark",
LIGHT: "light"
};
export const MATCH_DARK_THEME = "(prefers-color-scheme: dark)";
export const IS_USER_PREFERNCE_DARK =
window.matchMedia && window.matchMedia(MATCH_DARK_THEME).matches;
export const DEFAULT_THEME =
localStorage.getItem(LOCAL_STORAGE_KEY) || IS_USER_PREFERNCE_DARK
? THEMES.DARK
: THEMES.LIGHT;
export const theme = writable(DEFAULT_THEME);
因为没有 DI 存储在测试之间共享,所以我可以在 beforeEach 中将值重置为默认值,但尝试查看是否有更好的解决方案。
ThemeSwitcher.spec.js
it("should be change body class on click", async () => {
const { container } = render(ThemeSwitcher);
expect(container.className).toEqual("theme-light");
await fireEvent.click(getButton(container));
expect(container.className).toEqual("theme-dark");
});
it("should render the sun if in light mode", async () => {
const { getByText } = render(ThemeSwitcher);
//default should be light mode but returns dark.
const sun = getByText("Light theme on: Sun");
expect(sun).toBeTruthy();
});