Jest + Enzyme测试:如何确保将某些功能作为道具传递给组件 [英] Jest + Enzyme test: how to ensure a certain function is passed as prop to a component

查看:113
本文介绍了Jest + Enzyme测试:如何确保将某些功能作为道具传递给组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试一个具有多个嵌套组件的React组件。我的测试旨在确保为每个组件提供正确的道具。这些组件之一应该传递给onChange 函数,因此我尝试执行以下操作(在 test()内部):

I am testing a React component that has several nested components within. My tests aim to make sure each component is given the right props. One of those components should be passed an onChange function, so I tried to do the following (inside test()):

开玩笑+酶测试:

const props = {
  onSomethingChange: jest.fn()
};

const component = shallow(<MyComponent {...props} />);

expect(component.find('SomeNestedComponent')
  .prop('onSomethingChange')).toBe(props.onSomethingChange);

测试失败,并显示以下内容(注意:我也尝试过 .toEqual ):

The test fails with the following (note: I also tried .toEqual):

Expected value to equal:
  [Function mockConstructor]
Received:
  [Function anonymous]

我的组件的定义如下:

MyComponent

class MyComponent extends Component {
  onSomethingChange = (event) => {
    // do something
  }

  render() {
    return (
      <div>
        <Header />
        <SomeNestedComponent onSomethingChange={this.onSomethingChange} />
        <Footer />
      </div>
    );
  }
}

如何确定正确的函数传递为道具(而不仅仅是任何其他功能)?请注意,我不会随时调用该函数;我只是定义它。

How can I make sure the correct function is passed as prop (and not just any other function)? Note that I don't call the function anytime; I just define it.

推荐答案

我发现问题中的构造出了什么问题。问题是 onSomethingChange 函数是组件实例方法,而不是 MyComponent 组件本身。因此, SomeNestedComponent 中的 onSomethingChange 道具指的是 onSomethingChange MyComponent 中的方法(因此不等于其在测试中设置的属性)。解决方法是将 SomeNestedComponent 的prop与 MyComponent instance方法进行比较,如下所示:

I found out what is wrong with the construct in the question. The problem is the onSomethingChange function is a component instance method and not a prop of the MyComponent component itself. So the onSomethingChange prop in SomeNestedComponent was referring to the onSomethingChange method in MyComponent (thus not being equal to its prop set up in the test). The fix is to simply compare SomeNestedComponent's prop to MyComponent's instance method as follows:

expect(component.find('SomeNestedComponent')
  .prop('onSomethingChange')).toBe(component.instance().onSomethingChange);

instance()函数将使您获得所有可用的函数在组件中。

The instance() function will allow you to get all the functions available within the component.

这篇关于Jest + Enzyme测试:如何确保将某些功能作为道具传递给组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆