简体   繁体   中英

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 of jest.mock must 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);

  });
});

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM