Initial commit
This commit is contained in:
62
__tests__/features/theme-context.test.tsx
Normal file
62
__tests__/features/theme-context.test.tsx
Normal file
@ -0,0 +1,62 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { ThemeProvider, useTheme } from "@/lib/contexts/theme-context";
|
||||
|
||||
// 测试组件
|
||||
function TestComponent() {
|
||||
const { theme, setTheme, isDark } = useTheme();
|
||||
return (
|
||||
<div>
|
||||
<span data-testid="theme">{theme}</span>
|
||||
<span data-testid="isDark">{isDark.toString()}</span>
|
||||
<button onClick={() => setTheme("dark")}>Set Dark</button>
|
||||
<button onClick={() => setTheme("light")}>Set Light</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
describe("ThemeContext", () => {
|
||||
beforeEach(() => {
|
||||
// 清除 localStorage
|
||||
localStorage.clear();
|
||||
// 清除 document 的 class
|
||||
document.documentElement.classList.remove("dark");
|
||||
document.body.classList.remove("dark");
|
||||
});
|
||||
|
||||
it("should provide default theme", () => {
|
||||
render(
|
||||
<ThemeProvider>
|
||||
<TestComponent />
|
||||
</ThemeProvider>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("theme").textContent).toBe("light");
|
||||
expect(screen.getByTestId("isDark").textContent).toBe("false");
|
||||
});
|
||||
|
||||
it("should load theme from localStorage", () => {
|
||||
localStorage.setItem("theme", "dark");
|
||||
|
||||
render(
|
||||
<ThemeProvider>
|
||||
<TestComponent />
|
||||
</ThemeProvider>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("theme").textContent).toBe("dark");
|
||||
expect(screen.getByTestId("isDark").textContent).toBe("true");
|
||||
});
|
||||
|
||||
it("should apply dark class to document", () => {
|
||||
localStorage.setItem("theme", "dark");
|
||||
|
||||
render(
|
||||
<ThemeProvider>
|
||||
<TestComponent />
|
||||
</ThemeProvider>
|
||||
);
|
||||
|
||||
expect(document.documentElement.classList.contains("dark")).toBe(true);
|
||||
expect(document.body.classList.contains("dark")).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user