Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);

  });
});
like image 793
Richard Fernandez Avatar asked Oct 30 '25 14:10

Richard Fernandez


2 Answers

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 />);
like image 161
Jackson Kamya Avatar answered Nov 02 '25 04:11

Jackson Kamya


The proper mocking of the components would be something like this:

const mockComponent = () => <div>table</div>
jest.mock('./Table', () => mockComponent)
like image 24
Maciej Trojniarz Avatar answered Nov 02 '25 02:11

Maciej Trojniarz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!