React 测试库无法使用 Tailwind CSS 类读取样式

Ahm*_*sam 12 reactjs jestjs tailwind-css react-testing-library

我有一个简单的 React 组件,最初有一个 Tailwind CSS 类,hidden该类应用 CSSdisplay: none并将该类更改为visible单击按钮。当我用expect().not.toBeVisible()它进行测试时,它告诉我该元素在具有类时已经可见hidden

如果我不使用 Tailwind CSS 并使用法线,style={{display: 'none'}}它将正确识别该元素不可见。这显然意味着问题出在 Tailwind CSS 上。

这是我的测试:

test("Notification bar should be initially hidden but visible on click", async () => {
    render(<Notifications />);

    expect(await screen.findByTestId("list")).not.toBeVisible();
    // this test fails while the element already has a Tailwind CSS class of "hidden"
});
Run Code Online (Sandbox Code Playgroud)

虽然这是我的组件:

<ul className="hidden" data-testid="list">
  <li>item 1</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

Var*_*aya 6

Stack Overflow中解释的解决方案:无法检查 Expectelm not tobevisible for Semantic ui React component。基于该线程,我扩展了该解决方案,使其与 TailwindCSS 一起使用,如下所述的步骤,

\n

项目结构

\n
root/\n   src/\n      test/\n         index.css\n         test-utils.tsx\n         component.test.tsx\n      index.css\n
Run Code Online (Sandbox Code Playgroud)\n

1. 从 TailwindCSS 模板文件生成 CSS

\n

通过发出下面的命令,调用的 CSS 文件将在目录index.css中生成src/test

\n
npx tailwindcss -i ./src/index.css -o ./src/test/index.css\n
Run Code Online (Sandbox Code Playgroud)\n

进一步阅读:TailwindCSS 安装

\n

2. 创建自定义渲染函数

\n

接下来我们需要将生成的 CSS 文件注入到 JSDOM 中。自定义渲染函数将很有用,因此我们不需要为每个测试重复此任务

\n
import { render, RenderOptions } from \'@testing-library/react\';\nimport React, { FC, ReactElement } from \'react\';\nimport fs from \'fs\';\n\nconst wrapper: FC<{ children: React.ReactNode }> = ({ children }) => {\n  return <>{children}<>;\n};\n\nconst customRender = (ui: ReactElement, options?: Omit<RenderOptions, \'wrapper\'>) => {\n  const view = render(ui, { wrapper, ...options });\n\n  const style = document.createElement(\'style\');\n  style.innerHTML = fs.readFileSync(\'src/test/index.css\', \'utf8\');\n  document.head.appendChild(style);\n\n  return view;\n};\n\nexport * from \'@testing-library/react\';\nexport { customRender as render };\n
Run Code Online (Sandbox Code Playgroud)\n

进一步阅读:测试库设置

\n

3. 进行测试,单元测试现在应该成功了

\n
import React from \'react\';\nimport { render, screen } from \'./test-utils\';\n\ntest(\'Renders hidden hello world\', () => {\n  render(<span className="hidden">Hello World</span>);\n  expect(screen.getByText(\'Hello World\')).not.toBeVisible();\n});\n
Run Code Online (Sandbox Code Playgroud)\n

为什么我们不使用toHaveClass匹配器呢?

\n

它不符合\xe2\x80\x9c 的测试库指导原则,强调重点关注与用户交互的网页方式非常相似的测试\xe2\x80\x9c,因为这样做,你正在与组件不自然

\n