【发布时间】:2019-09-07 20:35:25
【问题描述】:
我第一次尝试使用 React 上下文 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
感谢您的帮助
【问题讨论】:
-
请以文本形式发布代码 sn-ps,而不是屏幕截图。
标签: reactjs unit-testing jestjs enzyme react-context