当使用酶进行单元测试时,没有执行react useEffect

问题描述 投票:0回答:2

我有一个使用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();
    });

});

我有一个使用useEffect的组件,它对称为props.getPostsInit()的redux操作进行api调用。我将如何测试它,到现在为止我收到一个错误,它没有调用getPostsInit ...

reactjs jestjs enzyme
2个回答
1
投票

关于功能组件,酶促浅层渲染API不够健壮(截至2020年2月),无法处理功能组件的各种情况。


0
投票

我需要更改

© www.soinside.com 2019 - 2024. All rights reserved.