1

I have a component with the following code

<Resizable
  ...
  onResizeStop={(e, direction, ref, d) => {
    someFunc(d.width)
  }}
  ...
>

I want to test the onResizeStop prop. I could make a new named function and assign it to the prop but I am not very willing to change the original code for testing purposes.

What should be the ideal way to test this prop. Do I need to make a mock function? How do I compare the real prop value and the expected value?

0

1 Answer 1

2

Mock functions usually capture all the calls performed to the function and provide a way to inspect how many time the mock was called and the arguments it was called with.

Jest's mock functions make no exception.

// Initialize your mock function
const onResizeStopMock = jest.fn();

// Setup your component with React test renderer or Enzyme or any other React renderer tool
<Resizable
  onResizeStop={onResizeStopMock}
>

// Interact with your component and inspect the mock function, eg:

// Mock function was called only once
expect(onResizeStopMock.mock.calls.length).toBe(1);

// Test the fourth argument of the first call ("d")
expect(onResizeStopMock.mock.calls[0][3]).toEqual({width: 99, height: 99});
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Andrea, thanks for the help. I was wondering what should be the approach if the Resizable component is part of a big component being tested. How would we set that particular prop to a mock function? Ideally, I would be doing <MyComponent props={...props}/> for my setup. This approach doesn't cover the setup for Resizable
When something is hard to unit test, 95% of the times it means there is an underlying architectural decision waiting to be improved. A big component wrapping other components as a black box smells like a not optimal solution. I see at least 2 solutions in your case: make the big component composable or at least let the big component accept the callback functions of its children via props.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.