有没有办法等待在Jest/Enzyme中触发异步功能的事件



我有一个向导包含步骤,每个步骤都有自己的验证(sync/async(。

例如:

<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块中,您可以将匿名函数指定为异步函数,如下所示:

it('should do some stuff...', async () => {

然后在tree.find方法之前,添加 await 关键字

await tree.find('onContinue-button').simulate('click');

最新更新