cy.clock 和 cy.tick 不使用拆分代码

cy.clock and cy.tick not working with split code

假设我的 React.js 项目中有一个 setInterval,它是从 15 秒到 0 秒的倒计时。但是我想在 e2e 测试中加快这个过程,因为 15 秒可能是 60、120 甚至 240 秒。

所以,这段代码有效:

describe('Test timer', () => {

  before(() => {
    cy.clock()
    cy.visit('http://localhost:3000')
  })

  it('Displays timer, pass 15 seconds, does not display timer', () => {
    cy.get('div [data-cy=counterText]').should('have.text', '15');
    cy.tick(15000);
    cy.get('div [data-cy=counterText]').should('have.text', '0');
  })
})

但是在项目中我通常会这样拆分一些代码:

describe('Test timer', () => {

  before(() => {
    cy.clock()
  })

  it('Visit site', () => {
    cy.visit('http://localhost:3000')
  })

  it('displays timer', () => {
    cy.get('div [data-cy=counterText]').should('have.text', '15');
  })

  it('does not display timer', () => {
    cy.tick(15000);
    cy.get('div [data-cy=counterText]').should('have.text', '0');
  })
})

问题是,上面的代码给我以下错误信息:

cy.tick() cannot be called without first calling cy.clock()

我已经尝试将 cy.clock() 移动到不同的地方但没有成功,所以问题是:在上面的用例中我应该把 cy.clock() 放在哪里?

我正在使用 Cypress 8.X,以防万一。

提前致谢!

您必须保留 clock instance,因为(我认为)测试之间的清理会影响您期望的模式。

您还需要在勾选时关闭日志记录,因为日志记录代码中存在错误。 (没有深入探讨)。

describe('Test timer', () => {

  let clock
  before(() => {
    cy.clock().then(c => clock = c)
  })

  it('Visit site', () => {
    cy.visit('http://localhost:3000')
  })

  it('displays timer', () => {
    cy.get('div [data-cy=counterText]').should('have.text', '15');
  })

  it('does not display timer', () => {
    clock.tick(15000, {log: false});
    cy.get('div [data-cy=counterText]').should('have.text', '0');
  })
})

用于测试的简单应用程序

<div>
  <div id="counter" data-cy="counterText">15</div>
</div>
<script>
  let intervalID = setInterval(() => {
    const div = document.getElementById('counter')
    const newText = +div.innerText - 1
    console.log(`setting ${newText}`)
    div.innerText = newText
    if (newText < 1) {
      clearInterval(intervalID)
    }
  }, 1000)
</script>