Using Jest to mock a React component with props

There’s a note at the bottom of the docs for jest.mock() for preventing the hoisting behavior:

Note: When using babel-jest, calls to mock will automatically be
hoisted to the top of the code block. Use doMock if you want to
explicitly avoid this behavior.

Then you can do as you described: return a function that is a stub of the component you don’t need to test.

jest.doMock('./ComponentToMock', () => {
  const ComponentToMock = () => <div />;
  return ComponentToMock;
});

const ComponentToTest = require('./ComponentToTest').default;

It’s helpful to name the stub component since it gets rendered in snapshots.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)