scriobh
scriobh

Reputation: 890

How to test a method which is in mapStateToProps in React using Jest - Enzyme

I'm not able to increase coverage for this line handleSave which I'm passing as a prop to my component. However, I'm importing mapStateToProps from my container file in the test case and used .toBeTruthy() for validating the test case.

Here's a gist of my code

export const mapStateToProps = (state, ownProps) => {
  return {
    handleSave: title => ownProps.history.push(setTitle(title)),
  };
};

This is the test case that I wrote

it('mapStateToProps test case', () => {
  const result = mapStateToProps(state, ownProps);
  expect(result.handleSave).toBeTruthy();
});

Could anyone please help? What should I do to get the handleSave covered?

Upvotes: 1

Views: 486

Answers (1)

Subesh Bhandari
Subesh Bhandari

Reputation: 1112

What you can do is mock the ownProps and test out the mock function like:

const mockFn = jest.fn();
const ownProps = {
 history: {
   push: mockFn
 }
}

const result = mapStateToProps(state, ownProps);

// Now call the handle save function
result.handleSave("My title");


// And then as follows:

// This will ensure that your function is calling ownProps history push method.
expect(mockFn).toBeCalled();

// To check the funciton has only been called once
expect(mockFn.mock.calls.length).toBe(1);


// This is to check if the correct argument has been passed. Be sure to pass in what your `setTitle` funciton returns 
expect(mockFn.mock.calls[0][0]).toBe("My title");

Upvotes: 1

Related Questions