[英]How do I test theme toggler with react testing library and jest?
I am trying to test whether the bg color changes after clicking the theme toggler.我正在尝试测试单击主题切换器后 bg 颜色是否发生变化。
test("Toggle changes from light to dark mode", () => {
render(<DashboardPage />);
const themeToggler = screen.getByRole("button");
const dashboardBackground = screen.getByTestId("dashboard-menu");
expect(themeToggler).toBeInTheDocument();
expect(dashboardBackground).toHaveStyle(
"background-color: rgb(255, 255, 255)"
);
userEvent.click(themeToggler);
expect(dashboardBackground).toHaveStyle("background-color: rgb(0,0,0)");
});
I have wrapped my components with ThemeProvider, but the background-color remains white even after clicking.我用 ThemeProvider 包装了我的组件,但即使在单击后背景颜色仍然是白色。
If you are using @testing-library/user-event
, when you should use async
functions and wait until user similated events ends up如果您正在使用@testing-library/user-event
,您应该何时使用async
函数并等待用户模拟事件结束
test("Toggle changes from light to dark mode", async () => {
render(<DashboardPage />);
const themeToggler = screen.getByRole("button");
const dashboardBackground = screen.getByTestId("dashboard-menu");
expect(themeToggler).toBeInTheDocument();
expect(dashboardBackground).toHaveStyle(
"background-color: rgb(255, 255, 255)"
);
await userEvent.click(themeToggler);
expect(dashboardBackground).toHaveStyle("background-color: rgb(0,0,0)");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.