reactjs - 使用 Enzyme 浅层而不是安装来测试使用 useEffect 的组件

标签 reactjs enzyme

// MyComponent.jsx
const MyComponent = (props) => {
  const { fetchSomeData } = props;

  useEffect(()=> {
    fetchSomeData();
  }, []);

  return (
    // Some other components here
  )
};

// MyComponent.react.test.jsx
...
describe('MyComponent', () => {
  test('useEffect', () => {
    const props = {
      fetchSomeData: jest.fn(),
    };

    const wrapper = shallow(<MyComponent {...props} />);

    // THIS DOES NOT WORK, HOW CAN I FIX IT?
    expect(props.fetchSomeData).toHaveBeenCalled();
  });
});



运行测试时我得到:

expect(jest.fn()).toHaveBeenCalled()

Expected mock function to have been called, but it was not called.

expect 失败,因为 shallow 没有调用 useEffect。由于其他问题,我无法使用 mount,需要找到一种方法使其使用 shallow 工作。

最佳答案

useEffect Enzyme's shallow rendering 不支持。是on the roadmap (参见“v16.8+:Hooks”栏)将在下一版本的 Enzyme 中修复,如 ljharb 中提到的

当前设置无法实现您所要求的内容。然而,a lot of people are struggling with this .

我已经解决/解决了这个问题:

这里总结了如何模拟模块,基于 Mock Modules来自 React 文档。

contact.js

import React from "react";
import Map from "./map";

function Contact(props) {
  return (
    <div>
      <p>
        Contact us via foo@bar.com
      </p>
      <Map center={props.center} />
    </div>
  );
}

contact.test.js

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";

import Contact from "./contact";
import MockedMap from "./map";

jest.mock("./map", () => {
  return function DummyMap(props) {
    return (
      <p>A dummy map.</p>
    );
  };
});

it("should render contact information", () => {
  const center = { lat: 0, long: 0 };
  act(() => {
    render(
      <Contact
        name="Joni Baez"
        email="test@example.com"
        site="http://test.com"
        center={center}
      />,
      container
    );
  });
});

有用的资源:

关于reactjs - 使用 Enzyme 浅层而不是安装来测试使用 useEffect 的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59164027/

相关文章:

unit-testing - 用 enzyme 测试react-intl组件

javascript - react : why does the onclick get executed even without having clicked?

clojure - 带联合的查询组合如何与通过 Om Next 中的 props 传递的父子树配合使用

javascript - (ReactJS + Redux) 当/new 添加到 url 时,表单未加载

javascript - 在 React Native 中运行 mount() 不可能吗?

javascript - 相同的代码在不同的机器上生成不同的快照

javascript - Enzyme 的模拟()不会更改 onChange 事件的输出

javascript - 我的函数计算总价格值,但总是落后一步?

javascript - Bundle.js 不接受任何更改

reactjs - window.history.back() 没有被调用 - Jest enzyme