我第一次尝试使用 React context API 将信息从主组件传递到孙组件。
首先我创建了一个上下文
const MyContext = React.createContext({});
export default MyContext;
这里是设置上下文值的主要组件
import MyContext from "./MyContext.js";
import ParentComponent from "./ParentComponent.js";
function App() {
return (
<div>
<MyContext.Provider value={{ foo: 12 }}>
<ParentComponent />
</MyContext.Provider>
</div>
);
}
父组件不关心上下文,只是创建孙组件
import ChildComponent from "./ChildComponent.js";
class ParentComponent extends Component {
render() {
return (
<div>
Parent
<ChildComponent />
</div>
);
}
}
export default ParentComponent;
这是读取上下文的子组件
import MyContext from "./MyContext.js";
class ChildComponent extends PureComponent {
constructor() {
super();
this.state = {
bar: 456
};
}
render() {
return (
<div>
<MyContext.Consumer>
{({ foo }) => (
<div>
<h1>Hello I'm the ChildComponent</h1>
<h2>Context value: {foo}</h2>
<h2>State value: {this.state.bar}</h2>
<button onClick={() => this.setState({ bar: foo })}>
Click me
</button>
</div>
)}
</MyContext.Consumer>
</div>
);
}
}
export default ChildComponent;
到目前为止没有问题。一切都按预期进行。 ChildComponent 已检索上下文值。
当我尝试用 jest/enzyme 测试它时,问题就出现了。我无法设置上下文
it("Should test the context value", () => {
let wrapper = mount(<ChildComponent />, {
context: { foo: 987 }
});
expect(wrapper.state("bar")).toEqual(456);
expect(wrapper.context("foo")).toEqual(987);
});
最后一个期望失败并且上下文值为空对象。所以 foo 未定义
我在这里重现了这个问题: https://codesandbox.io/embed/x25yop4x5w?fontsize=14
感谢您的帮助
最佳答案
我用来测试需要安装在上下文提供程序树中的组件的方法是使用 wrappingComponent
和 wrappingComponentProps
options for mount .
这可以确保 mount(根组件)的返回值仍然是您要测试的组件(并且仍然支持仅适用于根组件的 API/选项,例如 setProps
)。
mount(<MyComponent />, {
wrappingComponent: MyContext.Provider,
wrappingComponentProps: {
value: { foo: 987 },
},
})
关于reactjs - 单元测试: react context api with enzyme return an empty object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55730219/