2

我一直在阅读有关组件测试设置的文档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])

控制台仅显示...的 1 个打印件new Date()

4

1 回答 1

2

我认为出于同样的原因,您经常需要使用 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') 
于 2021-06-06T02:49:09.910 回答