Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest + Enzyme test: how to ensure a certain function is passed as prop to a component

Tags:

jestjs

enzyme

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()):

Jest + Enzyme Test:

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

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

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

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

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

The definition for my component follows:

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.

like image 340
nbkhope Avatar asked Feb 04 '23 22:02

nbkhope


1 Answers

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);

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

like image 163
nbkhope Avatar answered Feb 14 '23 16:02

nbkhope