【问题标题】:React testing library can't read styles using Tailwind CSS classesReact 测试库无法使用 Tailwind CSS 类读取样式
【发布时间】:2022-10-22 11:05:10
【问题描述】:

我有一个简单的 React 组件,它最初将具有 hidden 的 Tailwind CSS 类,它应用 CSS display: 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"
});

虽然这是我的组件:

<ul className="hidden" data-testid="list">
  <li>item 1</li>
</ul>

【问题讨论】:

  • 为什么不测试班级,鉴于基础样式不会应用于单元测试?

标签: reactjs jestjs tailwind-css react-testing-library


【解决方案1】:

Stack Overflow: cannot check expectelm not tobevisible for semantic ui react component 中解释了解决方案。基于该线程,我扩展了解决方案以使其与 TailwindCSS 一起使用,如下所述,

项目结构

root/
   src/
      test/
         index.css
         test-utils.tsx
         component.test.tsx
      index.css

1. 从 TailwindCSS 模板文件生成 CSS

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

npx tailwindcss -i ./src/index.css -o ./src/test/index.css

延伸阅读:TailwindCSS installation

2.创建自定义渲染函数

自定义渲染功能将很有用,因此我们不需要为每个测试重复此任务

import { render, RenderOptions } from '@testing-library/react';
import React, { FC, ReactElement } from 'react';
import fs from 'fs';

const wrapper: FC<{ children: React.ReactNode }> = ({ children }) => {
  return <>{children}<>;
};

const customRender = (ui: ReactElement, options?: Omit<RenderOptions, 'wrapper'>) => {
  const view = render(ui, { wrapper, ...options });

  const style = document.createElement('style');
  style.innerHTML = fs.readFileSync('src/test/index.css');
  document.head.appendChild(style);

  return view;
};

export * from '@testing-library/react';
export { customRender as render };

进一步阅读:

3.执行测试,单元测试假设现在成功

import React from 'react';
import { render, screen } from './test-utils';

test('Renders hidden hello world', () => {
  render(<span className="hidden">Hello World</span>);
  expect(screen.getByText('Hello World')).not.toBeVisible();
});

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 2022-06-21
    • 2022-06-16
    • 1970-01-01
    • 2021-09-25
    • 2022-11-04
    • 2022-12-13
    • 1970-01-01
    相关资源
    最近更新 更多