Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jest and Enzyme, how do I test a function passed in through props?

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?

like image 245
Heath Avatar asked Dec 11 '18 17:12

Heath


People also ask

How do you test a reaction using Jest and enzyme?

Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.

How do you test if a component is rendered with the right props when using React testing library?

Testing The ParentComponent is Setting Props Correctly render(<ParentComponent open data="some data" />); // Check that the Jest mock function is called with an object. // Use 'expect. objectContaining' to make sure any other default // React props are ignored. expect(mockChildComponent). toHaveBeenCalledWith( expect.


1 Answers

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();
});
like image 150
Herick Avatar answered Oct 04 '22 04:10

Herick