如何让测试用例等到 before() 执行完成?

How to make test case wait until before() execution finishes?

我正在使用 mocha 框架在 nodejs 中编写测试。由于我正在测试的端点是异步的,因此我使用了 ync-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)
})

对于 fecthContent 中的最后一次调用,您应该 await 因为它是异步的,否则测试会在它完成之前开始。 beforeEach 允许您 return 承诺等待其完成(参见 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);
}