javascript - 浅渲染一个组件,它是一个使用上下文的类
问题描述
我正在尝试使用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。那是对的吗?解决此问题的最佳方法是什么?
解决方案
推荐阅读
- sql - SQL 查询 GROUP BY MIN?
- c# - 无法在 XAML 中正确设置 RibbonGallery SelectedValue
- python - 如何在 python 中使用形状、位置和比例参数绘制 GEV 分布曲线
- gatling - 模拟组失败的最佳方法
- html - 在 html 输入文本上触发单击输入事件
- java - 尝试复制和重建项目时出现 Android Studio 错误
- c# - 使用自动滚动在面板上动态添加元素
- python - 有没有办法将 SVG 路径编码为点形状?
- kubernetes - 如何找出 Kubernetes 中可用的端口?
- html - 移除 HTML 元素的蓝色轮廓