Cypress cy.tick() 第二次调用时不转发时间

Cypress cy.tick() not forwarding time the second time it is called

我一直在阅读有关 cy.clock 的文档并将其与组件测试设置一起使用。但是我这里好像做错了什么

 it.only('shows an estimate on when it is ready (fulfilled)', () => {
    const now = new Date()
    cy.clock(now)

    mount(
      <ResizeWrapper>
        <CartProvider>
          <PaymentSucceededMessage />
        </CartProvider>
      </ResizeWrapper>
    )

    // Time left
    cy.contains('10 min', { matchCase: false }).should('be.visible')
    cy.tick(1000 /*ms*/ * 60 /*sec*/ * 1 /*min*/ + 300 /*ms*/)
    cy.contains('9 min', { matchCase: false }).should('be.visible')
    //  Something breaks here 
    cy.tick(1000 /*ms*/ * 60 /*sec*/ * 1 /*min*/ + 300 /*ms*/)
    cy.contains('8 min', { matchCase: false }).should('be.visible') // FIXME: The test does not work but the real life version does
  })

实施(目前)是这样的

  const [minutesLeft, minutesLeftSet] = React.useState<number>(10)


  React.useEffect(() => {
    let timer
    if (minutesLeft > 0) {
      timer = setTimeout(() => {
        console.log(new Date())
        minutesLeftSet((minutesLeft) => minutesLeft - 1)
      }, 1000 /*ms*/ * 60 /*sec*/ * 1 /*min*/)
    }

    return () => {
      if (timer) clearTimeout(timer)
    }
  }, [minutesLeft])

控制台只显示 new Date()...?

的 1 个打印件

我认为出于同样的原因,您经常需要使用 useState 的回调形式 setter,例如 minutesLeftSet((minutesLeft) => minutesLeft - 1),您还需要在测试中进行节拍以允许 React hooks 处理。

所以,这行得通

const now = new Date()
cy.clock(now)

mount(
  <ResizeWrapper>
    <CartProvider>
      <PaymentSucceededMessage />
    </CartProvider>
  </ResizeWrapper>
)

// Time left
cy.contains('10 min', { matchCase: false }).should('be.visible')

cy.tick(1000 /*ms*/ * 60 /*sec*/ * 1 /*min*/ + 300 /*ms*/)
cy.wait(0)                                                      // yield to React hooks
cy.contains('9 min', { matchCase: false }).should('be.visible')

cy.tick(1000 /*ms*/ * 60 /*sec*/ * 1 /*min*/ + 300 /*ms*/)
cy.wait(0)                                                      // yield to React hooks
cy.contains('8 min', { matchCase: false }).should('be.visible')