你如何在 React 测试中测试模拟上下文?
How do you test, mock context in React tests?
我有这样的代码:
render () {
...
const {
exampleMethod,
} = this.props;
const { getPath } = this.context;
const exampletData = exampleMethod(getPath());
...
}
在此示例中,我如何模拟、测试上下文?您通常如何测试上下文?
如果您正在使用 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() 方法
我有这样的代码:
render () {
...
const {
exampleMethod,
} = this.props;
const { getPath } = this.context;
const exampletData = exampleMethod(getPath());
...
}
在此示例中,我如何模拟、测试上下文?您通常如何测试上下文?
如果您正在使用 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