在摩卡中,如何在执行另一个测试之前等待异步测试结束?

In mocha, How to wait for the end of an asynchronous test before executing another test?

在 mocha 中我有两个测试:

因此,在执行第二个测试之前,我需要确保我的第一个测试已完全完成(这意味着我的第一个获取值的异步方法已完全完成)。

这是我的代码:

it('Should return a valid value ', () => {
    myService.check('value', (success) => {
        expect(success.isValid)
    });
})
it('Should put the value in cache', () => {
    return myService.getCached('value').then(result => {
        expect(result).to.be.ok;
    })
})

问题是第二个 'it' 在第一个完成之前启动...

我可以使用超时,例如:

it('Should return a valid value ', () => {
    myService.check('value', (success) => {
        expect(success.isValid)
    });
}).timeout(5000)
it('Should put the value in cache', () => {
    return myService.getCached('value').then(result => {
        expect(result).to.be.ok;
    })
})

但我不喜欢那样,它不是 100% 可靠的,我认为在两次测试之间我们不应该等待一个固定的时间值!

有更好的方法吗?

我会让你的测试独立且自我实现。所以,如果你想测试你的缓存,你应该缓存值并检查缓存中的值,就像这样:

it('Should put the value in cache', () => {
    myService.check('value1', (success) => {
        return myService.getCached('value1').then(result => {
            expect(result).to.be.ok;
        })
    });

})

如果您依赖其他测试 运行ning 在此之前,您是:

  • 如果有人移动代码,运行 会遇到问题
  • 如果之前的测试由于某种原因失败,将进入 运行 问题。您不希望依赖于其他测试通过