如何测试react.js中的模拟上下文?

如何测试react.js中的模拟上下文?

问题描述:

我有这样的代码:在这个例子中如何测试react.js中的模拟上下文?

render() { 
    ... 

    const { 
    exampleMethod, 
    } = this.props; 

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

    ... 
} 

我如何可以模拟,测试情境?一般来说,你如何测试上下文?

如果您使用的是enzyme,则可以通过传递选项来设置浅显示或全局渲染时的上下文。 (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()方法