我在两个模拟函数中都有一个prop模拟对象。我需要监视两个人,而且我不知道如何监视。
这是一个示例:
myComponent.js
function Package(props) {
const { lockUI } = props
lockUI.set();
// ...
}
myComponent.test.js
import React from 'react';
import Package from 'src/Package';
import { cleanup, render } from '@testing-library/react';
describe('Package Unit Test', () => {
let props;
beforeEach(() => {
props = {
lockUI : {
set : jest.fn(),
unset : jest.fn(),
},
};
});
afterEach(cleanup);
test('testing example', () => {
render(<Package {...props} />);
expect(props.lockUI.set).toHaveBeenCalledTimes(1);
});
});
响应控制台:
Expected number of calls: 1
Received number of calls: 0
答案 0 :(得分:1)
您只需要先声明setSpy和unsetSpy并将它们插入组件中即可
import React from 'react';
import Package from 'src/Package';
import { cleanup, render } from '@testing-library/react';
describe('Package Unit Test', () => {
const setSpy = jest.fn();
const unsetSpy = jest.fn();
let props;
beforeEach(() => {
props = {
lockUI : {
set : setSpy,
unset : unsetSpy,
},
};
});
afterEach(cleanup);
test('testing example', () => {
render(<Package {...props} />);
expect(setSpy).toHaveBeenCalledTimes(1);
});
});