简体   繁体   English

如何使用反应测试库和玩笑来测试主题切换器?

[英]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.

相关问题 我将如何使用 Jest 和 React 测试库对此进行测试? - How would I test this using Jest & React Testing library? 使用 Jest/React 测试库时,如何测试由 setInterval function 创建的 DOM 更改? - How do I test for DOM changes created by a setInterval function when using Jest/React testing library? 如何使用 Jest 和 React 测试库测试 className - How to test a className with the Jest and React testing library Jest + React 测试库:如何从某个库中模拟出只影响一个测试块的方法 - Jest + React Testing Library: how do I mock out a method from some library that only affects one test block 如何使用 onClick 函数 Jest/React 测试库测试 React 组件 - How to test react component with onClick function Jest/React testing library 如何使用 jest 和 react 测试库在 react 中测试路由 - how to test Routes in react using jest and react testing library 如何使用 Jest 和 react-testing-library 测试 react-dropzone? - How to test react-dropzone with Jest and react-testing-library? 如何使用 react 测试库 jest 测试下拉组件? - How to test a dropdown component in react using react testing library jest? 如何使用 React、Jest 和 React-testing-library 为带有令牌的 api 调用编写单元测试? - How can I write unit test for api call with token using React, Jest and React-testing-library? 如何测试与 Jest/react-testing-library 反应的上下文 - How can I test a context in react with Jest/react-testing-library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM