我正在尝试编写一个酶测试来单击一个开关,然后尝试另一个操作来手动调用该开关附带的功能。该函数更新状态。我无法通过任何一项测试。
在线上有太多不同的示例,这已经变得非常混乱。 有趣的是,在我使用MUI的createShallow之前,wrapper.instance()具有状态,而不是包装器。
组件
import React, { Component } from 'react';
import scss from './scss.module.scss';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Switch from '@material-ui/core/Switch';
import Drawer from '@material-ui/core/Drawer';
let styles = inlineStyles;
class Layout extends Component {
state = {
edit: false,
};
render () {
const { classes } = this.props;
return (
<div id="LayoutId" className={scss.layout}>
<Drawer>
</Drawer>
<AppBar>
<Toolbar>
<FormGroup row className={classes.EditSwitch}>
<FormControlLabel
control={
<Switch
id={'editSwitchId'}
checked={this.state.edit}
onChange={this.handleChange('edit')}
value="edit"
color="primary"
/>
}
label="Edit"
/>
</FormGroup>
</Toolbar>
</AppBar>
</div>
)
}
浅测
describe('Invoking "handleChange" method', () => {
let shallow;
beforeAll(() => {
shallow = createShallow({ dive: true });
});
it('renders Landing Page', (done) => {
const wrapper = shallow(<Layout />);
const instance = wrapper.instance();
instance.handleChange('adminEdit',{target:{checked:true}});
wrapper.update();
expect(instance.state.adminEdit).toBe(true);
done();
});
});
安装测试
describe('indirectly testing "handleChange" through click simulation', () => {
it('should update the edit state', () => {
const wrapper = mount(<Layout />);
wrapper.setState({
edit: true,
});
expect(wrapper.state('edit')).toBe(true);
let AllFoundSwitchIds = wrapper.find('#editSwitchId').hostNodes();
const event = {target: {checked: !wrapper.state().edit}};
AllFoundSwitchIds.props().val = false;
AllFoundSwitchIds.simulate('change', event);
wrapper.update();
expect(wrapper.state('edit')).toBe(false);
});
});