你如何在React测试中测试,模拟上下文?

时间:2017-12-18 10:28:48

标签: reactjs unit-testing jestjs enzyme

我有这样的代码:

render () {
  ...

  const {
    exampleMethod,
  } = this.props;

  const { getPath } = this.context;
  const exampletData = exampleMethod(getPath());

  ...
}

我如何在这个例子中模拟,测试上下文?你如何测试上下文?

1 个答案:

答案 0 :(得分:3)

如果您使用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()方法