在安装时测试useEffect函数调用

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

我在安装时有调用randomFunction的组件

// Example.js

import React, { useEffect } from 'react';

export const randomFunction = () => {
};

const Example = () => {
    useEffect(() => {
        randomFunction()
    }, []);

    return <div/>
};

export default Example;

并且在测试是否在安装时调用randomFunction时,测试失败。这是测试:

import React from 'react';
import { mount } from 'enzyme';
import Example, { randomFunction } from "./Example";

jest.mock('./Example', () => ({
    ...(jest.requireActual('./Example')),
    randomFunction: jest.fn()
}));

describe("<Example />", () => {
    describe("mount", () => {
        beforeEach(() => {
            mount(<Example/>);
        });

        it("calls randomFunction", () => {
            expect(randomFunction).toHaveBeenCalled(); // test fails
        });
    });
});

谁能帮我弄清楚如何正确测试吗?

版本:

"enzyme": "3.10.0",
 "enzyme-adapter-react-16": "^1.15.1"
  react + react dom: latest

谢谢

reactjs jestjs enzyme
1个回答
0
投票

嗯,你可以试试吗?

const mockRandomFunction = jest.fn();
jest.mock('./Example', () => ({
    ...(jest.requireActual('./Example')),
    randomFunction: mockRandomFunction
}));

然后

expect(mockRandomFunction).toHaveBeenCalled(); 
© www.soinside.com 2019 - 2024. All rights reserved.