【发布时间】:2021-01-06 10:26:18
【问题描述】:
我正在使用 Jest 和 Enzyme 为我的 react 项目编写单元测试。
如下图,我通过props将一个名为updateUser的函数传递给待测组件EditCard。
describe('The EditCard screen', () => {
let wrapper;
beforeEach(() => {
const defaultProps: Partial<EditCardProps> = {
toggleEditing: jest.fn(),
user: mockUsers[0],
updateUser: jest.fn(), // passes this function to the "EditCard" component via props
showSnackbar: jest.fn(),
};
wrapper = shallow(<EditCard {...(defaultProps as EditCardProps)} />);
});
那我想测试一下模拟点击按钮后被调用了多少次。
it('should match the snapshot when the "Name" textfield is not filled and the "submit" button is clicked', () => {
wrapper.find('#Name').simulate('change', { target: { value: null } });
wrapper.find('#submit').simulate('click');
// Try to get the "updateUser" function from the props, but get "undefined".
expect(wrapper.prop('updateUser')).toHaveBeenCalledTimes(0);
});
但是我得到了如下所示的错误:
Matcher error: received value must be a mock or spy function
Received has value: undefined
24 | wrapper.find('#Name').simulate('change', { target: { value: null } });
25 | wrapper.find('#submit').simulate('click');
> 26 | expect(wrapper.prop('updateUser')).toHaveBeenCalledTimes(0);
谁能告诉我哪里做错了?为什么我无法从 props 中获取函数并且返回了undefined?
提前致谢!
【问题讨论】:
标签: javascript reactjs jestjs enzyme