【问题标题】:How to make test case wait until before() execution finishes?如何让测试用例等到 before() 执行完成?
【发布时间】:2019-08-21 22:09:00
【问题描述】:

我正在使用 mocha 框架在 nodejs 中编写测试。由于我正在测试的端点是异步的,因此我使用了 aync-await 概念。但是测试用例不等待 before() 执行部分完成运行,即;异步函数,因此显示 listAll() api 的错误结果。

async function fetchContent() {
    const [profile, user] = await Promise.all([api.profiles.list(), api.users.list()])

    params = {userId: user.items[0].id, label: 'Test', profileId: profile.items[0].id, token: authToken}
    testApi = new Api(params)
    testApi.profiles.create(params)
}

before(async () => {
    await fetchContent()
})

describe('Profiles API', () => {
    it('list profiles', done => {
        testApi.profiles.listAll().then(response => {
            console.log('list=', response)
        })
        done()
    })
})

我也尝试了 it(),如下所示,但 listAll() 仍然不显示作为 before() 执行的一部分创建的配置文件记录:

describe('Profiles API', () => {
    it('list profiles', async () => {
                const response = await testApi.profiles.listAll()
                console.log('list=', response)
})

【问题讨论】:

  • 函数fetchContent内部最后一次调用testApi.profiles.create(params)是异步的吗?
  • @SamuelVaillant 是的 create() 是异步的,listAll() in it() test 也是如此。

标签: node.js async-await mocha.js


【解决方案1】:

您应该在fecthContent 中进行最后一次调用await,因为它是异步的,否则测试在完成之前就开始了。 beforeEach 允许您返回一个等待其完成的承诺(参见 Mocha 文档)。

async function fetchContent() {
  const [profile, user] = await Promise.all([
    api.profiles.list(),
    api.users.list()
  ]);

  params = {
    userId: user.items[0].id,
    label: "Test",
    profileId: profile.items[0].id,
    token: authToken
  };

  testApi = new Api(params);

  // This call is asynchronous we have to wait
  await testApi.profiles.create(params);
}

【讨论】:

  • 感谢塞缪尔提到这一点。我用 beforeEach() 替换了 before() 并等待 aync create() ,现在测试用例工作正常;listAll() 显示正确的响应。但是我有一个疑问 - before() 不会像 beforeEach() 那样返回承诺
  • @SoC 我认为他们都支持承诺模式。该问题与没有等待 create 函数有关。使用before,它也应该可以按预期工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 2020-11-02
  • 2017-06-15
相关资源
最近更新 更多