【问题标题】:Is there an way to wait for event that trigger async function in Jest/Enzyme?有没有办法等待在 Jest/Enzyme 中触发异步功能的事件?
【发布时间】:2019-08-21 16:26:42
【问题描述】:

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

例如:

<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。

谢谢。

【问题讨论】:

标签: reactjs jestjs enzyme


【解决方案1】:

step 变量没有按预期增加的原因是因为onContinue 是一个async 函数,并且您的测试文件没有尝试等待响应。由于它是异步的,并且您将其视为普通函数,因此代码继续执行而无需等待结果。

尝试这样做,看看是否有帮助,

在您的it 块中,您可以将匿名函数指定为异步,如下所示:

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

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

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

【讨论】:

  • 我一直在努力让它工作,但等待似乎只是偶然而不是设计。还有一个race condition,因为模拟没有返回实际等待的承诺。
猜你喜欢
  • 1970-01-01
  • 2021-01-25
  • 2022-01-25
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多