Javascript Jest测试未在子组件中触发父onClick函数
因此,我正在测试下面的子组件,它从父组件的prop中接收函数:Javascript Jest测试未在子组件中触发父onClick函数,javascript,reactjs,enzyme,jestjs,Javascript,Reactjs,Enzyme,Jestjs,因此,我正在测试下面的子组件,它从父组件的prop中接收函数: export interface IProps{ parentClick: () => void; } export class Child extends React.Component<IProps, {}> { handleClick = () => { this.props.parentClick(); } render () { return ( <
export interface IProps{
parentClick: () => void;
}
export class Child extends React.Component<IProps, {}> {
handleClick = () => {
this.props.parentClick();
}
render () {
return ( <button onClick={this.handleClick}>Click me</button> )
}
}
但测试失败的原因是:
预期模拟函数被调用了一次,但调用了零次。
我如何解决这个问题?我很惊讶您在
mount()上没有出现错误
,因为子类
应该未定义,或者由于常量与已定义的类具有相同的名称而导致引用错误。尝试对常量使用小写名称:const child
。这是一个输入错误。在我的代码中是小写的。
it("button click fires", () => {
const props = {
parentClick: jest.fn();
}
const Child = enzyme.mount(<Child {...props} />);
Child.find('button').simulate('click'); //shouldn't this trigger parentClick?
expect(props.parentClick).toHaveBeenCalled();
});