如何测试回调单击从父组件传递的子组件

如何测试回调单击从父组件传递的子组件

本文介绍了如何测试回调单击从父组件传递的子组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下父级组件:

import React, { Fragment } from 'react';

export class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
    };
  }

  onClick = () => {
    // working
  }

  render() {

    return (
      <Fragment>
        <Child handleClick={this.onClick} />
      </Fragment>
    );
  }
}

我需要检查子组件是否触发了回调, onClick方法将在父组件中触发。
我写了这样一个测试:

I need to check if callback fired in Child component, onClick method will be fired in Parent component.I wrote such a test:

test("check callback fire", () => {
    let mockFn = jest.fn();
    Parent.prototype.onClick = mockFn;

    let wrapper = shallow(<Parent />);

    wrapper.find('Child').props().handleClick();

    expect(mockFn).toHaveBeenCalled();
  });

我遇到了一个错误

 Expected mock function to have been called, but it was not called.

我怎样才能通过玩笑和酵素正确地做到这一点?

How can I do that properly with jest and enzyme? Is it possible?

推荐答案

问题出在 onClick 方法,如果您这样声明函数

the problem comes from the declaration of the onClick method, if you declare your function like this

onClick() {}

而不是

onClick = () => {}

您的测试应该可以正常运行,因为 onClick 将出现在 Parent.prototype 对象中,请注意 onClick this 关键字/ code>方法将不再引用类实例。

your test should work because onClick will be present in the Parent.prototype object, note that this keyword in the onClick method will no longer refers to the class instance.

如果需要使用箭头功能(获取正确的 this ),则可以修改测试:

If you need to use arrow function (to get the correct value of this), you could modify your test :

test("check callback fire", () => {
  let mockFn = jest.fn();

  let wrapper = shallow(<Parent />);
  wrapper.instance().onClick = mockFn;

  wrapper.find('Child').props().handleClick();

  expect(mockFn).toHaveBeenCalled();
});

使用 onClick =()=> Parent 类中的{} 不会将该属性添加到 Parent.prototype 中,实际上它将声明一个实例变量,如下所示:

Using onClick = () => {} in the Parent class will not add the property to Parent.prototype, in fact it will declare an instance variable like this :

class Parent {
  constructor() {
    super();
    this.onClick = () => {}
  }
}

顺便说一句,<$ render 方法中的c $ c> Fragment 似乎没有用,您可以将其删除

By the way, the presence of Fragment inside your render method seems to be useless, you could remove it

render() {
  return <Child handleClick={this.onClick} />;
}

这篇关于如何测试回调单击从父组件传递的子组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:58