简体   繁体   English

开玩笑错误:未捕获 [TypeError:XXX 不是函数]

[英]Jest Error: Uncaught [TypeError: XXX is not a function]

I've a onClick on component1 that calls a hook in component2 passing props to him:我在 component1 上有一个 onClick ,它在 component2 中调用一个钩子,将道具传递给他:

component1:组件1:

function test(){
    return(
       <div
          onClick=(() => this.props.changeExample(this.props.example)}
       />
}

component2 :组件2

changeExample(example){
    ...do some things
}

But when I try to test the onClick event of component1 with the following code:但是当我尝试使用以下代码测试 component1 的 onClick 事件时:

it("test onClick", () =>{
    let wrapper
     wrapper = shallow <component1 />
     const eventWrapper = wrapper.find("div")
     eventWrapper.simulate("click")
}

I got the following error:我收到以下错误:

Error: Uncaught [TypeError: _this.props.changeExample is not a function]错误:未捕获 [TypeError:_this.props.changeExample 不是函数]

You would need to mock that prop, then you can check if it have been called, something like:您需要模拟该道具,然后您可以检查它是否已被调用,例如:

it("test onClick", () => {
  const mockOnClick = jest.fn();
  const wrapper = shallow <component1 changeExample={mockOnClick} />

  const eventWrapper = wrapper.find("div");
  eventWrapper.simulate("click");

  expect(mockOnClick).toHaveBeenCalledTimes(1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM