我有一个组件使用useEffect
对其进行名为props.getPostsInit();
的redux操作的api调用
从现在开始,我将如何测试此错误,它没有调用getPostsInit属性
● <Dashboard/> › Should execute getPostsInit
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
仪表板
function Dashboard(props: dashboardProps) {
// const [title, setTitle] = useState<string>("");
// const [content, setContent] = useState<string>("");
// const [value, setValue] = useState<number>(0);
const didMountRef = useRef<Object>();
useEffect(() => {
if (!didMountRef.current) {
props.getPostsInit();
props.initCommentUpdates();
} else {
console.log("this is component didupdate");
}
}, []); // array prevents an infinite loop
......
Dashboard.test
import React from "react";
import { DashboardComponent as Dashboard } from "./dashboard";
import { shallow, mount, render } from "enzyme";
import PostForm from "../../components/forms/createPost/createPost";
describe("<Dashboard/>", () => {
let wrapper;
let useEffect;
const mockUseEffect = () => {
useEffect.mockImplementationOnce((f) => f());
};
const props = {
getPostsInit: jest.fn(),
getPopPostsInit: jest.fn(),
deletePostInit: jest.fn(),
postCommentInit: jest.fn(),
titleError: Boolean,
bodyError: Boolean,
posts: [],
error: [],
title: "Test",
postContent: "Another test",
addTitle: jest.fn(),
addContent: jest.fn(),
popPosts: [],
createPostInit: jest.fn(),
likePost: jest.fn(),
dislikePost: jest.fn(),
initCommentUpdates: jest.fn(),
};
beforeEach(() => {
useEffect = jest.spyOn(React, "useEffect");
mockUseEffect();
wrapper = shallow(<Dashboard {...props} />);
});
it("Should render dashboard component", () => {
expect(wrapper).toHaveLength(1);
});
it("Should execute getPostsInit", () => {
expect(props.getPostsInit).toHaveBeenCalled();
});
});
答案 0 :(得分:1)
关于功能组件,酶促浅层渲染API不够健壮(截至2020年2月),无法处理功能组件的各种情况。
您可能需要使用mount()完全渲染它。
wrapper = mount(<Dashboard {...props} />);
答案 1 :(得分:0)
jest.spyOn(React, "useEffect");
正在寻找React.useEffect
而不是useEffect
我需要改变
useEffect(() => {
if (!didMountRef.current) {
props.getPostsInit();
props.initCommentUpdates();
console.log("test");
} else {
console.log("this is component didupdate");
}
}, []); // array prevents an infinite loop
到
React.useEffect(() => {
if (!didMountRef.current) {
props.getPostsInit();
props.initCommentUpdates();
console.log("test");
} else {
console.log("this is component didupdate");
}
}, []); // array prevents an infinite loop
现在工作正常,我在测试中看到console.log("test")