代码之家  ›  专栏  ›  技术社区  ›  The Walrus

检查初始函数promise中promise后的状态

  •  0
  • The Walrus  · 技术社区  · 6 年前

    我有这个功能:

      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() 但那没什么用

    1 回复  |  直到 6 年前
        1
  •  0
  •   TLadd    6 年前

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