从未使用过Legacy Context,并且its doc page很差。要测试依赖于上下文的组件,您必须传递该上下文,并且选项很少。
- 酶的
mount()
/ shallow()
提供了second argument options
,可用于传递上下文。但是我不确定它是否适用于旧版上下文
const 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>)
如果有可能更喜欢使用现代的Context API,那就少了很多。
PS为什么您需要在构造函数中访问context
?如果您在render()
中使用它,则不必担心“上下文已更新,但是render()
仍引用旧值”。
,
事实上,即使对于旧的上下文,传递带有上下文属性的选项也能解决问题。
假设我们有 color
上下文 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://www.f2er.com/3154362.html