呈现子组件时无法设置上下文

Unable to set context when rendering child components

本文关键字:设置 上下文 组件      更新时间:2023-09-26

我试图测试自定义Material-ui React组件与酶,但得到以下错误:

ERROR: 'Warning: Failed context type: Required context 'muiTheme' was not specified in 'ChildComponent'.

我所尝试的是根据这个设置一个上下文。我想要到达和测试的组件是一个子组件。

const root = shallow(<RootComponent />, {context: {muiTheme}, childContextTypes: {muiTheme: React.PropTypes.object}})
const child = root.find(ChildComponent)
child.render() // <--- this line is throwing the error

我不确定这是解决方案,但它离目标又近了一步。

const root = mount(<RootComponent />, {
  context: {muiTheme},
  childContextTypes: {muiTheme: React.PropTypes.object}
})
const child = root.find(ChildComponent)

注意,我用mount代替shallow。问题是,我不能再使用child.find({prop: 'value'}) -返回0项…

您需要提供<muiThemeProvider>组件。

下面是一个关于如何做的例子:

import React from 'react';
import { mount } from 'enzyme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Input from './Input';
describe('<Input />', () => {
    const mountWithTheme = (node) => mount(<MuiThemeProvider>{node}</MuiThemeProvider>);
    it('calls componentDidMount', () => {
        sinon.spy(Input.prototype, 'componentDidMount');
        mountWithTheme(<Input />);
        expect(Input.prototype.componentDidMount.calledOnce).to.equal(true);
    });
});