Search code examples
javascriptreactjsunit-testingmockingjestjs

Jest Mock React Component


I'm using a plugin that renders out a form using json schema. For elements like input, button, etc, it uses a React component within the structure to render out the component. In our app, we receive schema json that describes the layout. For example, we could receive something like this (simplified to make it easier to read)

{
  component: 'input'
}

and I have a convertor function that places the component in where one is detected in the structure. It will send something do like: (again, simplified)

import Table from './Table';

covert(schema) {
  return {
    component: Table // where table is: (props:any) => JSX.Element
  }
}

I want to write a test for this, but having trouble with the comparing the result with the expected. In my test, I mock the Table component and send through a named mock function as the second param. Then I use the same named param in the expected results.

I get an error back: The second argument ofjest.mockmust be an inline function. I can change this to an inline function, but then how can I use this in the expected structure used for comparison?

// Test code


import React from 'react';

const mockComponent = () => <div>table</div>
jest.mock('./Table', mockComponent);

const schema = {
  component: 'table'
}

describe('Component Structure', () => {
  test('componentizes the schema structure', () => {

    const results = convert(schema);
    const expected = {
      component: mockComponent
    };
    expect(results).toEqual(expected);

  });
});

Solution

  • The error is because you are not mocking the component properly, the right way should be:

    jest.mock('./Table', () => mockComponent);
    

    given that you already have mockComponent defined as:

    const mockComponent = () => <div>table</div>
    

    or you could do:

    jest.mock('./Table', () => () => <div />);