我在安装时有调用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
谢谢
嗯,你可以试试吗?
const mockRandomFunction = jest.fn();
jest.mock('./Example', () => ({
...(jest.requireActual('./Example')),
randomFunction: mockRandomFunction
}));
然后
expect(mockRandomFunction).toHaveBeenCalled();