Jest 模拟 React 组件

Ric*_*aly 4 javascript unit-testing mocking reactjs jestjs

我正在使用一个插件,它使用 json 模式呈现表单。对于输入、按钮等元素,它使用结构中的 React 组件来渲染组件。在我们的应用程序中,我们收到描述布局的模式 json。例如,我们可以收到这样的内容(简化以使其更易于阅读)

{
  component: 'input'
}

Run Code Online (Sandbox Code Playgroud)

我有一个转换器函数,可以将组件放置在结构中检测到的位置。它将发送如下内容:(再次简化)

import Table from './Table';

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

我想为此编写一个测试,但无法将结果与预期进行比较。在我的测试中,我模拟了 Table 组件,并通过命名的模拟函数作为第二个参数发送。然后我在预期结果中使用相同的命名参数。

我收到错误:The second argument ofjest.mock must be an inline function。我可以将其更改为内联函数,但是如何在用于比较的预期结构中使用它?

// 测试代码


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

  });
});
Run Code Online (Sandbox Code Playgroud)

jac*_*dev 7

错误是因为您没有正确模拟组件,正确的方法应该是:

jest.mock('./Table', () => mockComponent);
Run Code Online (Sandbox Code Playgroud)

鉴于您已经将 mockComponent 定义为:

const mockComponent = () => <div>table</div>
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做:

jest.mock('./Table', () => () => <div />);
Run Code Online (Sandbox Code Playgroud)