How to mock function that returns JSX Element

Viewed 102

I have a function, that returns JSX Element.

  myFunction.jsx
  const myFunction = (props) => {
  // ... do something with props
  
  return <MyElement {...newProps} />
}


// MyElement.jsx
export const MyElement = (props) => {
   // ... return some jsx
}

My goal is to check that myFunction returns an element with correct set of props. But I don't want to include render of MyComponent to test, so I mocked it. I tried to test it like this:

const mockFn = jest.fn();
jest.mock('.../path-to-my-component/MyComponent, () => ({
  MyComponent: (props) => {
    mockFn(props) 
    return 'my-component'
  }
}))

// ....

myFunction(someProps)
expect(mockFn).toHaveBeenCalled() // mockFn have been called 0 times
expect(mockFn).toHaveBeenCalledWith(someProps)

But both expects were failed.

2 Answers

That's how I finally handle it

jest.mock('../../MyComponent', () => ({
  MyComponent: (props) => {
    return <div {...props} />;
  },
}));

test('my test', () => {
  const Component = myFunction(props);
  expect(Component.props).toBe(/* that's the place where you can check props */)
});

Something like this could allow you to not render myComponent if it's props are not the way you want after they have been check by propsIsOk

// myFunction.jsx
const myFunction = (props) => {
  // ... do something with props
  const propsIsOk = (props) => {
    // Check props' properties and returns a boolean 
  }
  if(propsIsOk(newProps)){
    return(<MyElement {...newProps} />)
  } else {
    return(<></>)
  }
}

// MyElement.jsx
export const MyElement = (props) => {
  // ... return some jsx
}
Related