在初始函数承诺中检查承诺后的状态



我有这个功能:

  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()但这并没有真正做任何事情

更改 startGame 函数以返回承诺。还要修复其他人提到的设置超时问题。它应该看起来像这样

  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);
});

最新更新