// 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 .
我已经解决/解决了这个问题:
- 不再使用 Enzyme 的浅层渲染
- 使用React Testing Library代替 enzyme
- 通过 Jest 模拟模块
这里总结了如何模拟模块,基于 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/