【问题标题】:CSS Modules not working as expected in tests with Jest and Enzyme, using create-react-appCSS 模块在 Jest 和 Enzyme 的测试中没有按预期工作,使用 create-react-app
【发布时间】:2021-03-03 19:32:21
【问题描述】:

我在 CRA 应用程序中使用 CSS 模块。我的组件如下所示:

import HeaderStyles from './Header.module.scss';

const Header: FunctionComponent<HeaderProps> = ({
// Props
}) => (
  <div className={HeaderStyles['header-container']}>
  // Some other stuff
)

我的测试是这样的:

    const component = shallow(
      <Header />
    );

    expect(component.find('.header-container')).toBeTruthy();

我希望它会失败,因为类名应该有所不同,因为我使用的是 CSS 模块。我在这里遗漏了什么吗?

【问题讨论】:

    标签: reactjs jestjs enzyme react-css-modules


    【解决方案1】:

    我研究并发现 jest 或 react-scripts 只加载一个空对象而不是那个样式模块。我猜他们使用了另一个加载器或其他东西,但这在单元测试中有点酷,你只需要测试你的包或加载器的一部分,而不是其他包的工作方式,所以这很好。

    奇怪的是,任何实习生都会从查询HeaderStyles['header-container']开始,导致测试无效,并且会花费更多时间。

    所以我的建议是改用patch-styles,它更具声明性并消除了测试中的陌生感。使用 PatchStyles,您需要将代码更改为

    <PatchStyles classNames={HeaderStyles}>
      <div className="header-container">...</div>
    </PatchStyles>
    

    它会自动应用 HeaderStyles 而不是你。有关详细信息,请查看 StackBlitz 示例。

    【讨论】:

      猜你喜欢
      • 2022-08-16
      • 2020-04-21
      • 2017-07-04
      • 2019-01-30
      • 1970-01-01
      • 2017-02-12
      • 2017-11-26
      • 1970-01-01
      • 2017-11-10
      相关资源
      最近更新 更多