【问题标题】:How do you test, mock context in React tests?你如何在 React 测试中测试、模拟上下文?
【发布时间】:2023-03-18 10:00:01
【问题描述】:
我有这样的代码:
render () {
...
const {
exampleMethod,
} = this.props;
const { getPath } = this.context;
const exampletData = exampleMethod(getPath());
...
}
如何在这个例子中模拟、测试上下文?以及一般如何测试上下文?
【问题讨论】:
标签:
reactjs
unit-testing
jestjs
enzyme
【解决方案1】:
如果您使用enzyme,您可以通过传递一个选项来设置浅渲染或全dom渲染时的上下文。 (docs here):
例如:
import { shallow, mount } from 'enzyme';
// ......
const testContext = { getPath: () => 'foo' };
const shallowWrapper = shallow(<SomeComponent />, { context: testContext });
// or
const fullWrapper = mount(<SomeComponent />, { context: testContext });
如果你想在一个节点上测试上下文,你可以使用enzyme中的.context()方法