【问题标题】:Test react components with jest and enzyme and css modules使用 jest 和酶和 css 模块测试反应组件
【发布时间】:2019-11-28 11:45:56
【问题描述】:

我有一个使用 create react app 创建的项目。 假设我有一个像这样的简单组件 -

import React from 'react';

import React, { useState } from "react";

function Example() {
  const [data, setData] = useState(0);
  const onClickHandler = () => {
    setData(data + 1);
  };

  return (
    <div className="button" onClick={onClickHandler}>
      {data}
    </div>
  );
}

export default Example;

我会像这样测试组件 -

import React from "react";
import { shallow } from "enzyme";
import Example from "./Example";

it("example test", () => {
  const wrraper = shallow(<Example />);
  wrraper.find(".button").simulate("click");
  expect("test somethig");
});

如果我会像这样使用styles.module -

import React, { useState } from "react";
import styles from "./styles.module.scss";

function Example() {
  const [data, setData] = useState(0);
  const onClickHandler = () => {
    setData(data + 1);
  };

  return (
    <div className={styles.button} onClick={onClickHandler}>
      {data}
    </div>
  );
}

export default Example;

我将无法再使用“.button”在测试中找到元素,因为当我使用 css 模块时,webpack 会在我的类名中添加一个哈希。 那么如何在使用 css 模块时测试反应组件?仅通过向元素添加 Id ? 更改我的代码是错误的,因此我将能够对其进行测试。

谢谢, 迪娜

【问题讨论】:

    标签: reactjs jestjs enzyme css-modules react-create-app


    【解决方案1】:

    有许多替代选择器,您可以找到here。也就是说,在使用 (s)css 模块时,我倾向于依赖组件中的元素位置:

    wrapper.find("div").first() 将选择组件层次结构中的第一个 div 元素(或者在您的示例中,它将选择具有“styles.button”类名的 div)。

    另一种选择是使用template literals。通过下面的示例,我基本上创建了一个逃生舱口来选择.some-classname

    import React, { useCallback, useState } from "react";
    import { button } from "./styles.module.scss";
    
    function Example() {
      const [data, setData] = useState(0);
      const onClickHandler = useCallback(() => {
        setData(prevSate => prevState + 1);
      }, [setData]);
    
      return (
        <div className={`${button} some-classname`} onClick={onClickHandler}>
          {data}
        </div>
      );
    }
    
    export default Example;
    

    最后,你可以使用data-attribute——比如data-test-id(因为react-testing-library而变得越来越流行)来创建一个简单的静态选择器,可以使用额外的babel插件来删除它以用于生产构建) .

    【讨论】:

      【解决方案2】:

      我参加聚会有点晚了,但我自己也在想这个。您只需要将 scss 模块导入您的测试文件,如下所示:

      import React from "react";
      import { shallow } from "enzyme";
      import Example from "./Example";
      import styles from "./styles.module.scss
      
      it("example test", () => {
        const wrraper = shallow(<Example />);
        wraper.find(`.${styles.button}`).simulate("click");
        expect("test somethig");
      });
      

      【讨论】:

        猜你喜欢
        • 2020-08-22
        • 2018-09-12
        • 2019-05-13
        • 2021-11-26
        • 1970-01-01
        • 1970-01-01
        • 2019-04-24
        • 2020-08-11
        • 2017-08-16
        相关资源
        最近更新 更多