我正在测试一个组件,该组件呈现具有以下contextTypes的子组件:
Component.contextTypes = {router: PropTypes.object.isRequired}
我是开玩笑的新手,但是来自摩卡/酶我从未遇到过这个问题。
我的第一个测试看起来像这样,我真的只是搞乱它看看它是如何工作的:
it('should exist', () => {
wrapper = renderer.create(<Companies/>);
let tree = wrapper.toJSON();
expect(tree).toMatchScreenshot();
});
当我运行测试时,我收到以下错误:
Failed context type: The context `router` is marked as required in `ChildComponent`, but its value is `undefined`.
是否有解决方法,或者只是我缺少的文档中的某些内容?提前谢谢!
解决方案:对于遇到同一问题的任何人,我在beforeEach()中使用了以下内容:
MyComponent.contextTypes = {
router: function () {
return {
transitionTo: jest.genMockFunction()
};
}
};
答案 0 :(得分:5)
当我在某个组件中使用<Link>
时遇到类似问题,并遇到与上述相同的错误。
在我的情况下,我使用的是react-router 4.1.1,上面的解决方案没有用。
我在上下文中添加了对象和函数,但我希望有人能为我提供更好的解决方案。
describe('SomeComponent', ()=>{
it('renders component', ()=>{
const wrapper = mount(
<SomeComponent />,
{
context: {
router: {
history: {
push: ()=>{},
replace: ()=>{},
createHref: ()=>{},
}
}
},
childContextTypes: {
router: PropTypes.object.isRequired,
}
}
)
expect(wrapper.text()).toContain('some component text')
})
})
我使用酶mount
。