我有这个功能:
startGame = () => {
this.buildDeck()
.then(this.shuffleDeck)
.then(this.dealToPlayer)
.then(setTimeout(this.dealToPlayer, 2000))
.then(setTimeout(this.dealToDealer, 4000))
}
我试图通过这样做来测试它:
it('expects playersHand to have 2 cards once game started', () => {
wrapper.instance().startGame();
expect(wrapper.state('playersHand').length).toEqual(2);
});
然而,它说收到0因为我相信它不等待完全执行的承诺。在运行测试之前,我怎么能等待承诺完成?
我已经尝试了.update()
,但这并没有真正做任何事情
答案 0 :(得分:0)
更改您的startGame函数以返回承诺。还修复了其他人提到的setTimeout问题。看起来应该是这样的
startGame = () => {
return this.buildDeck()
.then(this.shuffleDeck)
.then(this.dealToPlayer)
.then(() => setTimeout(this.dealToPlayer, 2000))
.then(() => setTimeout(this.dealToDealer, 4000))
}
你有两种不同类型的异步;承诺和计时器。您需要确保承诺已经解决并且计时器已经运行,然后才能进行断言。您可以使用这样的测试(假设您正在使用Jest):
it('expects playersHand to have 2 cards once game started', async () => {
jest.useFakeTimers();
await wrapper.instance().startGame();
jest.runAllTimers();
expect(wrapper.state('playersHand').length).toEqual(2);
});