我正在尝试使用 Jest/Enzyme 测试具有 Vertical Stepper 的注册组件,但在尝试模拟用户单击“下一步”时,我一直碰壁。
- 如果“必填”输入字段为空,预期的行为是不执行任何操作,但是在执行 .simulate('click') 后,以下断言失败,在包装器中找不到任何 html。
组件通过 react-redux connect() 传递,所以我不知道这是否相关。
UserRegistration.js
import React from 'react';
import { connect } from 'react-redux';
import Stepper from '@material-ui/core/Stepper';
import Step from '@material-ui/core/Step;
import StepLabel from '@material-ui/core/StepLabel;
import StepContent from '@material-ui/core/StepContent'
class UserRegistration extends React.Component {
constructor(props){
this.state = {
activeStep: 0,
inputData: {},
...
}
}
getStepContent = () => {
switch(this.state.activeStep)
case '...':
return
(<>
<input test-data="firstName"/>
...
</>);
...
}
render () {
const steps = ['Personal Info', 'Corporate Details', ...]
return (
<Stepper activeStep={this.state.activeStep} orientation="vertical">
{steps.map((label, index) => {
return (
<Step key={index}/>
<StepLabel>{label}</StepLabel>
<StepContent>
{this.getStepContent()}
<button data-test="btn-next" onClick={() => this.goNext()}> NEXT </button>
<button onClick={() => this.goBack()}> BACK </button>
)
}
}
</Stepper>
)
}
}
const mapStateToProps = () => {...}
const mapDispatchToProps = () => {...}
export default connect(mapStateToProps, mapDispatchToProps)(UserRegistration)
UserRegistration.test.js
const wrapper = mount(
<Provider store={store}
<UserCreate/>
</Provider>
)
it('Confirm REQUIRED fields rendered', () => {
expect(wrapper.find("input[data-test='firstName']").length).toEqual(1);
// PASS
});
it('Check if still on same step clicked NEXT with no user data', () => {
wrapper.find("button[data-test='btn-next']").simulate('click');
expect(wrapper.find("input[data-test='firstName']").length).toEqual(1);
// Expected value to equal: 1, Received: 0
})
无论我查找的是什么元素,结果都是一样的。
任何建议将不胜感激。
最佳答案
你需要更新。所以你会改变它:
it('Check if still on same step clicked NEXT with no user data', () => {
wrapper.find("button[data-test='btn-next']").simulate('click');
// Add this line
wrapper.update();
const button = wrapper.find("input[data-test='firstName']");
expect(button.length).toEqual(1);
// Expected value to equal: 1, Received: 0
});
然后测试应该按您的预期进行。
关于javascript - 在 React App 中模拟 ('click' 后 enzyme 安装包装器为空),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59786476/