next.js 如何使用React测试库和vitest测试主题切换器?

nx7onnlm  于 2022-11-05  发布在  React
关注(0)|答案(1)|浏览(222)

我正在使用TypeScriptTailwind.css创建一个web应用程序。为了测试,我使用了vitest @testing-library/react @testing-library/user-event
我已经创建了一个主题上下文来切换黑暗主题的打开和关闭。我只是简单地将 tailwinddark类切换到bodyclassList
当我手动测试应用程序(通过点击)时,功能运行正常。但是,单元测试失败了。下面是我的测试片段:

describe("toggle theme functionality -- Landing page", async () => {
const btn = screen.getAllByRole("themetoggler")[0];

const before = document.body.classList.contains("dark");
await e.click(btn);
const after = document.body.classList.contains("dark");

expect(after).toBe(!before);
});

我做错了什么?
ps:themetoggler是我分配给切换按钮的role

qltillow

qltillow1#

我终于解决了这个问题,我回答我自己的问题,以便它可能会帮助别人在未来。
最初,我将父组件呈现为render(<Landing />),但我忘记考虑到该组件无法访问ThemeContextProvider,这就是为什么每当单击按钮时,都不会触发与上下文相关的回调。
以下是我解决此问题的方法:

const { unmount } = render(
<ThemeContextProvider>
  <Landing />
</ThemeContextProvider>
);

现在,组件可以访问上下文值,在本例中是themeToggler按钮功能。
下面是下面其余代码的代码片段:

it("should not contain the 'dark' class initially attached to the body", () => {
  const beforeToggling = document.body.classList.contains("dark");
  expect(beforeToggling).toBe(false);
});

it("should toggle the 'dark' class on/off from the body", async () => {
  const btn = screen.getByRole("button");
  const beforeToggling = document.body.classList.contains("dark");
  await userEvent.click(btn);
  const afterToggling = document.body.classList.contains("dark");

  expect(beforeToggling).not.toBe(afterToggling);
});

相关问题