5
votes

Using Jest and Enzyme, how can I test if this.props.functionToTest was run?

class TestComponent extends Component {
   static propTypes = {
     functionToTest: PropTypes.func
   }
   componentDidMount() {
     this.props.functionToTest()
   }
}

In Jest, I've tried creating mockProps and passing them in when mounting the component.

let props = {
  functionToTest = jest.fn(() => {});
}
beforeEach(() => {
  const wrapper = mount(<TestComponent {...props} />
}

A console.log in the componentDidMount function shows functionToTest as undefined. Obviously passing in the props during mount isn't working.

Question 1: How can I pass in mock props that will show in the componentDidMount function?

Question 2: Once that function is available, how do I gain access to the function so I can use spyOn or something similar to test if the function was run?

2

2 Answers

6
votes

I don't know your exact setup, but this is how I would do that:

  • Mock the function with jest.fn() like you did
  • Pass mock to the component being mounted (like apparently you did)
  • Check whether it was run with expect(...).toBeCalled() or .toHaveBeenCalled() (varies between different Jest versions)

.

let props = {
  functionToTest: jest.fn() // You don't need to define the implementation if it's empty
};

beforeEach(() => {
  const wrapper = mount(<TestComponent {...props} />
}

// In the test code:
it('does something', () => {
    expect(props.functionToTest).toBeCalled();
    // OR... depending on your version of Jest
    expect(props.functionToTest).toHaveBeenCalled();
});
0
votes

The problem ended up being that TestComponent was only being exported within the Redux wrapper. Adding an export at the class level and destructuring it in the Jest test import, along with the solution Henrick posted above fixed it.