首页 > 解决方案 > 浅渲染一个组件,它是一个使用上下文的类

问题描述

我正在尝试使用shallow酶测试组件。我要测试的组件是一个类,并且像这样执行上下文:

class ExampleComponent extends Component {
  static contextType = AppContext;
  ...

并在该组件中使用它const { url } = this.context;

在编写测试时,已使用:

const contextWrapper = {
  wrappingComponent: AppContext,
  wrappingComponentProps: { url: 'http://appUrl.com' },
};

这里是以快照测试为例,它使用 mount,因为这似乎是让上下文工作的唯一方法。

it('should render correctly', () => {
  const output = mount(<Comonent {...props} />, contextWrapper);
  expect(shallowToJson(output)).toMatchSnapshot();
});

我做了一些重构,在这个文件中有一个连接到商店的组件。使用 mount 时,它希望为该组件提供一个商店,这就是我想要我们的原因shallow

Component如果我用 a包装,<Provider store={store}>我可以让它完成所有工作,但我有一个测试进一步尝试访问状态,Component但它是空白的并且找不到它。

这是未找到状态的测试片段:

const output = mount(
  <Provider store={store}>
    < ExampleComponent {...newProps} />
  </Provider>,
  contextWrapper,
);
expect(output.state('stateValue')).toBe(true);

这是显示的错误:

ReactWrapper::state("stateValue") requires that `state` not be `null` or `undefined`

有没有办法使用shallow和上下文?我发现这个包现在可以“修复”它,我不确定这是否正确?我还看到过旧帖子说酶不支持新的上下文 api。那是对的吗?解决此问题的最佳方法是什么?

标签: javascriptreactjsjestjsenzyme

解决方案


推荐阅读