开玩笑地测试收集到的onClick事件目标

用户名

我正在测试myFunction单击按钮时调用的方法。myFunction实际上只是调用另一个函数并传递一些东西给它,包括被单击的元素,我希望它实际上是img按钮内部。

例如:

<button class="button" onClick=myFunction(someArgs)>
   <img class="imageInsideButton" />
/>

  myFunction = (someArgs) => (event) => 
    this.props.someOtherFunction(
      someArgs
      event.target
    );

在我的测试中,我尝试检查是否someOtherFunction使用预期的args进行了调用,其中包括event.target

  function render(args, renderer = shallow) {
    const component = renderer(<MyComponent {...args} />);

    return {
      component,
      buttons: () => component.find(".button"),
      imagesInsideButtons: () => component.find(".imageInsideButton"),
    };
  }

  beforeEach(() => {
    myProps = {
      myFunction: jest.fn(),
    };
  });

  it("Should call someOtherFunction with the correct args", () => {
     const { buttons, imagesInsideButtons } = render(defaultArgs, mount);
     const indexClicked = 1;

     buttons().at(indexClicked).simulate("click");

     expect(myProps.someOtherFunction).toHaveBeenCalledWith(
         someArgs, imagesInsideButtons().at(indexClicked)
     );
  });

因此,在此测试中,我模拟了其中一个buttons()(在本例中为第二个)的点击。我希望单击的事件目标img是包装在此按钮内的事件目标

这样做确实可行,但问题似乎是我的测试期望一个ReactComponent但得到一个实际节点:

预期

其他参数ReactWrapper {}

已收到

其他参数 <button class="button"><img class"imageInsideButton" /></button>

就获得此事件目标而言,结果似乎还可以,但是我编写测试的方式意味着这些不匹配。如何使此测试有效?

亚历克斯特拉斯特罗

模拟点击,你可以通过假目标,并期望目标。

buttons().at(indexClicked).simulate("click", { target: 999 });

// test
expect(myProps.someOtherFunction).toHaveBeenCalledWith(
  someArgs, 999
);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章