我有一个包含步骤的向导,每个步骤都有自己的验证(同步/异步)。
例如:
<Wizard>
<Form1 />
<Form2 />
<Form3 />
</ Wizard>
每个表单都包含用于验证表单输入的onContinue
方法。
onContinue = async () => {
let step = this.steps[this.state.step];
let validation = await step.validate();
// check for error and change step number.
this.changeStep(this.state.step + 1, validation);
};
现在我正在尝试测试向导的行为,方法是确保单击“继续”时步骤编号增加 1。
it('should set the state property "step" to 1 after successfully clicking the continue button', () => {
const props = {
id: 'testId',
children: noErrorChildren
};
const wizard= mount(<Wizard {...props} />);
tree.find('onContinue-button').simulate('click');
expect(wizard.state().step).toEqual(1);
});
运行测试后,出现此错误:
Error: expect(received).toEqual(expected)
Expected value to equal:
1
Received:
0
Expected :1
Actual :0
step
变量没有按预期增加到 1。
谢谢。
最佳答案
step
变量没有按预期增加的原因是 onContinue
是一个 async
函数,并且您的测试文件没有尝试等待回复。由于它是异步的,并且您将其视为普通函数,因此代码会继续执行而不等待结果。
尝试这样做,看看是否有帮助,
在您的 it
block 中,您可以将匿名函数指定为异步,如下所示:
it('should do some stuff...', async () => {
然后在 tree.find
方法之前添加 await
关键字
await tree.find('onContinue-button').simulate('click');
关于reactjs - 有没有办法在 Jest/Enzyme 中等待触发异步函数的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55439293/