在一个项目中,我正在使用Jest和酶进行单元测试。我的组件是一个样式化的组件,它包裹了另一个组件。我的CvvFieldUi组件使用材质UI的TextField组件。这是我的代码
export class CvvFieldUI extends CvvFieldState {
render() {
const { classes } = this.props;
return (
<TextField
fullWidth
type={!this.state.showCvv ? "password" : "text"}
id="cvv-number"
placeholder={this.state.placeHolder}
value={this.state.cvvValue}
className={clsx(classes.textField)}
onChange={(event) => {
this.handleChange(event);
this.props.CVV(this.state.cvvValue);
}}
InputProps={{
classes: { root: classes.inputField },
endAdornment: (
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={(event) => this.handleClickShowPassword(event)}
onMouseDown={(event) => this.handleMouseDownPassword(event)}
>
{this.state.showCvv ? <Visibility /> : <VisibilityOff />}
</IconButton>
</InputAdornment>
),
}}
variant="outlined"
/>
);
}
}
CvvFieldUI.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(CvvFieldUI);
我想测试此组件的状态。这是我的代码。
test('Testing CVV Field', () => {
/*const { getByText } = render(<App />);
const linkElement = getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();*/
const wrapper = shallow(
<MuiThemeProvider theme={theme}>
<CvvFieldUI placeHolder="placeholder" CVV={()=>{}} />
</MuiThemeProvider>
).dive();
const input = wrapper.find(OriginalCvvField);
console.log("Child",input.state().cvvValue.length);
});
我所做的是从styledcomponent中获取展开的组件。但是当我这样做时,它给我错误
ShallowWrapper::state() can only be called on the root
看来我无法获得未样式化的组件。
问题:
如何在组件上调用状态方法?
更新:
现在,我正在测试可见的输出,但它也不起作用。它确实向我显示了input
及其属性,但是我无法对其进行操作。当我显示input的值时,它仍然显示null。这是我的代码
const wrapper = mount(
<MuiThemeProvider theme={theme}>
<CvvFieldUI placeHolder="placeholder" CVV={()=>{}} />
</MuiThemeProvider>
);
const Cvv=wrapper.find(OriginalCvvField);
const input = Cvv.find('input');
input.simulate('focus');
input.simulate('change', { target: { value: 'Changed' } });
console.log("Input tag",input.get(0));