Home > Blockchain >  How to properly mock named export children components with jest
How to properly mock named export children components with jest

Time:05-24

So, here is a simplified version of both my component and my test.

export const VerifyPositionsDialog = () => {
  return (
    <BaseVerifyPositionsDialog>
      <PositionsArea />
    </BaseVerifyPositionsDialog>
  );
};

I've omitted props and components logic for better readability.

What I've been trying to do is to mock PositionsArea component, so I can unit test VerifyPositionsDialog isolatedly.

This is my test so far.

jest.mock("../VerifyPositionsDialog/PositionsArea", () => ({
  __esModule: true,
  PositionsArea: () => <div />,
}));

render(<VerifyPositionsDialog />);

I've already tried a lot of different ways based on other answer from SO, but none seems to work. Any help would be awesome.

CodePudding user response:

You should mock the component using jest.fn returning the mocked div:

jest.mock('../VerifyPositionsDialog/PositionsArea', () =>
  jest.fn(() => <div>Mocked</div>),
);

describe('Test', () => {
  it('Mock Component Test', () => {
    const { debug } = render(<VerifyPositionsDialog  />);

    // You will check with debug() that mocked div was rendered
    debug();
  });
});
  • Related