简体   繁体   English

Jest Mock React 组件

[英]Jest Mock React Component

I'm using a plugin that renders out a form using json schema.我正在使用一个使用 json 模式呈现表单的插件。 For elements like input, button, etc, it uses a React component within the structure to render out the component.对于输入、按钮等元素,它使用结构内的 React 组件来渲染组件。 In our app, we receive schema json that describes the layout.在我们的应用程序中,我们收到描述布局的架构 json。 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.在我的测试中,我模拟了 Table 组件并通过一个命名的模拟函数作为第二个参数发送。 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 .我得到一个错误: jest.mock The second argument of 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:鉴于您已经将 mockComponent 定义为:

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

or you could do:或者你可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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