如何测试嵌入式异步调用 [英] how to test an embedded async call

查看:50
本文介绍了如何测试嵌入式异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试函数 parent(),该函数调用返回的函数 slomo().我想检查 .then()中的代码是否正在执行.

I am testing a function parent() that calls a function slomo() that returns a promise. I want to check that the code within the .then() is being executed.

function slomo() {
  return new Promise(function (resolve, reject) {
    resolve('good')
    reject('bad')
  })
}

child = jest.fn()

function parent() {
  slomo()
    .then((result) => {
      child()
    })
}

// TEST

it('runs child', () => {
  parent()
  expect(child).toHaveBeenCalledTimes(1)
})

结果是:

预期模拟函数被调用了一次,但被调用了零次.

Expected mock function to have been called one time, but it was called zero times.

我已确认通过 console.log 调用了子功能,但是在测试完成后 AFTER 已记录该子功能.
我尝试通过并在测试内调用 done ,但这不能解决问题.
也许上面的代码是反模式,需要重写才能进行测试?

I have confirmed the child function IS being called via console.log, but it is being logged AFTER the test has completed.
I have tried passing and calling done inside the test but that did not correct the issue.
Maybe the above code is an anti-pattern and needs to be rewritten so that it can be tested?

非常感谢您能给我的帮助!

Any help you can give me is greatly appreciated!

推荐答案

您正确地发现了问题的根本原因,即测试早于异步代码完成,因此

You correctly found the root case of the problem, that test finishes earlier then async code, so test should track async correctly. But seems to you lost the promise b/c you don't return it, so:

function parent() {
  return slomo() // <<<--- add return 
    .then((result) => {
      child()
    })
}

接下来,您只需添加完成:

it('runs child', (done) => { // <<<< --- add done
  parent().then(() => {
    expect(child).toHaveBeenCalledTimes(1)
    done(); // <<<< -- done should be called after all
  })
});

或只返回承诺:

it('runs child', () => {
  return parent().then(() => {  // <<<--- return
    expect(child).toHaveBeenCalledTimes(1);
  })
})

希望有帮助.

这篇关于如何测试嵌入式异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆