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

问题描述 投票:0回答:1

我有这个功能:

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

javascript reactjs enzyme
1个回答
0
投票

更改startGame函数以返回promise。还修复了其他人提到的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);
});
© www.soinside.com 2019 - 2024. All rights reserved.