我正在尝试使用Enzyme测试自定义Material-ui React组件,但收到以下错误:
ERROR: 'Warning: Failed context type: Required context 'muiTheme' was not specified in 'ChildComponent'.
我尝试过根据this设置上下文。我想要访问和测试的组件是子组件。
const root = shallow(<RootComponent />, {context: {muiTheme}, childContextTypes: {muiTheme: React.PropTypes.object}})
const child = root.find(ChildComponent)
child.render() // <--- this line is throwing the error
答案 0 :(得分:2)
我不确定这是解决方案,但距离目标更近了一步。
const root = mount(<RootComponent />, {
context: {muiTheme},
childContextTypes: {muiTheme: React.PropTypes.object}
})
const child = root.find(ChildComponent)
请注意,我使用mount
代替shallow
。问题是我不能再使用child.find({prop: 'value'})
- 返回0项......
答案 1 :(得分:1)
您需要提供<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);
});
});