使用浅酶和非挂载测试使用useEffect的组件 [英] Testing a component that uses useEffect using Enzyme shallow and not mount
本文介绍了使用浅酶和非挂载测试使用useEffect的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
// 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。由于其他问题,我无法使用装载,需要使用shallow
找到使其工作的方法。
推荐答案
所述,下一版本的酶需要修复on the roadmap(见‘v16.8+:hooks’一栏)您要求的内容在当前设置下是不可能的。但是,a lot of people are struggling with this。
我已通过以下方式解决/解决此问题:
- 不再使用酶的浅层渲染
- 使用React Testing Library而不是酶
- 通过Jest模拟模块
以下是关于如何基于Reaction文档中的Mock Modules模拟模块的摘要。
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
);
});
});
有用资源:
这篇关于使用浅酶和非挂载测试使用useEffect的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文