我的不完整测试会在TypeError: Cannot read property 'checked' of undefined
行引发错误renderer.create
。在我的应用程序的根级别渲染相同的组件时,它没有任何问题。使用renderer.create
的正确方法是什么,以便我可以检查组件的DOM结构?
测试:
import React from 'react';
import renderer from 'react-test-renderer';
import MultiSelect from '../multi_select';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
it('Test the stuff', () => {
let component = renderer.create(
<MuiThemeProvider>
<MultiSelect options={['a','b','c']} id='test'/>
</MuiThemeProvider>
);
});
组件:
import React, {Component} from 'react';
import CheckBox from 'material-ui/Checkbox';
/**
* `SelectField` can handle multiple selections. It is enabled with the `multiple` property.
*/
export default class MultiSelect extends Component {
/** Default constructor. */
constructor(props) {
super(props);
this.state = {
values: (props.values)? props.values : [],
options : (props.options)? props.options : [],
hintText : (props.id)? "Select " + props.id : "Select an option",
style : this.props.style
};
this.handleChange = (event, index, values) => this.setState({values});
}
menuItems(values) {
return this.state.options.map((name) => (
<CheckBox
key={name}
checked={values && values.indexOf(name) > -1}
value={name}
label={name}
onClick={this._toggle.bind(this, name)}
/>
));
}
_toggle(name) {
let currentValue = this.state.values;
let newValue = currentValue;
let exists = currentValue.some((item) => {
return item == name;
});
if (exists){
newValue = currentValue.filter((value) => {
return value != name;
});
} else {
newValue.push(name);
}
this.setState({values: newValue});
}
getValue() {
return this.state.values;
}
render() {
const {values, hintText} = this.state;
let greyOut = {color: 'rgba(0, 0, 0, 0.3)'}
return (
<div className="multi_select">
<span style={greyOut}>{hintText}</span>
{this.menuItems(values)}
</div>
);
}
}
.babelrc
{
presets: ["stage-2", "es2015", "react"]
}
答案 0 :(得分:0)
与这一个人搏斗了一下,最后找到了解决方法。
此评论引导我找到修复此问题的途径:https://github.com/facebook/react/issues/7740#issuecomment-247335106
基本上你需要传递一个模拟createNodeMock
作为react-test-renderer
的第二个参数:
test('checked', () => {
// Mock node - see https://reactjs.org/docs/test-renderer.html#ideas
const createNodeMock = element => {
return {
refs: {
checkbox: {
checked: true
}
}
}
};
const component = renderer.create(<Checkbox label="foo" />, { createNodeMock });
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});