我使用react-context保存我的数据并访问构造函数中的数据,如下所示:
class MyComponent extends Component {
//constructor
constructor(props, context) {
super(props, context);
const { testData } = this.context.storedData
this.state={
//maintained states
}
}
//constructor ends
}我试图使用jest和酶框架测试react-context,但得到的错误如下:
TypeError: Cannot read property 'testData ' of undefined
25 | constructor(props, context) {
26 | super(props, context);
> 27 | const { testData } = this.context.storedData
| ^我已经尝试了大多数解决方案,但都不起作用。我正在寻找适合我情况的完美解决方案。
发布于 2019-11-06 16:27:09
从来没有使用过遗留环境,而且its doc page相当差。要测试依赖于上下文的组件,您必须传递该上下文,并且有很少的选择。
mount()/shallow()提供了可用于传递上下文的second argument options。但我不确定它是否适用于旧版contextconst wrapper = mount(<MyComponent />, { context: {storedData: {testData: 1} } });function createWrapperForContext (contextData) {
return class Wrapper extends React.Component {
getChildContext() {
return contextData;
}
render() {
return this.props.children;
}
};
}
....
const ContextWrapper = createWrapperForContext(testData);
const elementWrapper = mount(<ContextWrapper><YourComponent /></ContextWrapper>) 如果有可能更喜欢迁移到现代的上下文API,那就麻烦多了。
PS为什么你需要在构造函数中访问context?如果你在render()中使用它,你就不会担心"context已经更新,但render()仍然引用旧值“。
发布于 2021-01-05 00:04:27
实际上,传递带有上下文属性的选项将修复即使对于遗留上下文也是如此。
假设我们有color context https://reactjs.org/docs/legacy-context.html。
测试将是:
import { shallow, ShallowWrapper } from 'enzyme';
import React from 'react';
describe('MyComponent', () => {
let component = ShallowWrapper<MyComponentProps>;
// This will test the default color value
it('should render with default context', () => {
component = shallow(<MyComponent {...props}/>);
expect(component).toMatchSnapshot();
});
// testing with different context
it('should render with context', () => {
component = shallow(<MyComponent {...props} />, {
context: {
color: 'red', // you still give it the default value.
},
});
component.setContext({ color: 'purple' });
component.instance().forceUpdate(); // you could call also render from instance
expect(component).toMatchSnapshot();
});
});https://stackoverflow.com/questions/58724755
复制相似问题