【发布时间】:2018-01-26 16:47:50
【问题描述】:
下面我不完整的测试在renderer.create 行上抛出错误TypeError: Cannot read property 'checked' of undefined。在我的应用程序的根级别呈现相同的组件时,它呈现没有问题。使用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"]
}
【问题讨论】:
-
刚刚尝试使用 react-test-context-provider 为 MultiSelect 组件提供 MuiThemeProvider 上下文。它的表现没有任何不同。
标签: javascript reactjs unit-testing material-ui jestjs