【发布时间】:2020-09-23 19:08:12
【问题描述】:
TLDR; 模拟从第三方库导入的 React 组件的正确方法是什么?
我正在测试一个名为 <App/> 的组件。它使用名为 <Localize/> 的第三部分组件,该组件由名为 localize-toolkit 的库提供。
我在使用 Jest 模拟 <Localize/> 时遇到了一些问题。
这是我尝试模拟它的方法。
jest.mock('localize-toolkit', () => ({
// Normally you pass in a key that represents the translated caption.
// For the sake of testing, I just want to return the key.
Localize: () => (key:string) => (<span>{key}</span>)
}));
我已经为<App/> 编写了一个单元测试,看起来像这样。
it('Test', () => {
const component = render(<App/>);
expect(component).toMatchSnapshot();
}
)
它会通过,但是这是返回的警告消息。
Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render.
当我查看快照时,我会看到一系列句点“...”,其中应该出现本地化标题。
我没有正确地模拟Localize 组件吗?
【问题讨论】: