我正在使用一个插件,它使用 json 模式呈现表单。对于输入、按钮等元素,它使用结构中的 React 组件来渲染组件。在我们的应用程序中,我们收到描述布局的模式 json。例如,我们可以收到这样的东西(简化以使其更易于阅读)
{
component: 'input'
}
我有一个转换器函数,可以将组件放置在结构中检测到的位置。它将发送如下内容:(再次简化)
import Table from './Table';
covert(schema) {
return {
component: Table // where table is: (props:any) => JSX.Element
}
}
我想为此编写一个测试,但无法将结果与预期进行比较。在我的测试中,我模拟了 Table 组件,并通过命名的模拟函数作为第二个参数发送。然后我在预期结果中使用相同的命名参数。
我收到错误:
The second argument of
jest.mockmust 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);
});
});
错误是因为你没有正确模拟组件,正确的方法应该是:
jest.mock('./Table', () => mockComponent);
假设您已经将mockComponent定义为:
const mockComponent = () => <div>table</div>
或者你可以这样做:
jest.mock('./Table', () => () => <div />);
组件的正确模拟应该是这样的:
const mockComponent = () => <div>table</div>
jest.mock('./Table', () => mockComponent)