cypress.js e2e 测试所有元素未定义

cypress.js e2e test all elements are undefined

我已经在大型应用程序上工作了一段时间,并且刚刚开始编写端到端测试。

应用为Vue-cli 3.0应用,原先默认测试平台'nightwatch',后来改为'cypress'。问题是,一个简单的登录测试有效,但任何比这更大的都会崩溃。

同一个应用程序,通过此代码测试:

import { email, password } from '../../testinfo'

describe('login test', () => {
  it('login', () => {
    cy.visit('/')
    cy.contains('#btnLogin', 'Login')
    // cy.contains('#btnSignUp', 'Sign up')
    cy.get('#btnLogin').click()
    cy.get('#input-email > input').type(email)
    cy.get('#input-pw > input').type(password)
    cy.get('#btnProceedLogin').click()
    cy.wait(3000)
    cy.contains('a', 'Team')
    cy.contains('a', 'Tournament')
  })
})

但是这段代码失败了:

import { email, password } from '../../testinfo'
import nanoid from 'nanoid'

describe('team related stuff test', () => {
  it('team creation and delete', () => {
    cy.visit('/')
    cy.contains('#btnLogin', 'Login')
    cy.contains('#btnSignUp', 'Sign up')
    cy.get('#btnLogin').click()
    cy.get('#input-email > input').type(email)
    cy.get('#input-pw > input').type(password)
    cy.get('#btnProceedLogin').click()
    cy.wait(3000)
    cy.get('#navTeam').should('exist')
    cy.get('#navTeam').trigger('mousedown')
    cy.get('.make > button').click()
    cy.get('#full-form-name > input').type(`[test]${nanoid}`)
    cy.get('#full-form-select-game > div > div > button').click()
    const gameMax = cy.get('#full-form-select-game > div > ul').length
    const targetGameIdx = Math.floor(Math.random() * gameMax)
    cy.get('#full-form-select-game > div > ul')[targetGameIdx].click()
  })
})

我无法理解的是第二个测试规范失败并显示一条消息 cannot read property click of undefined。我把cy.wait(3000)放在前面,或者我给它延迟都没有关系。

有趣的是,如果我将 cy.wait() 放在最前面,它应该至少等待 3 秒才能显示有关与元素交互的错误消息,但是一旦我启动应用程序,瞬间弹出错误信息。

您的问题在这里:

const gameMax = cy.get('#full-form-select-game > div > ul').length

您不能像这样存储值。您的代码 运行 在测试 运行 开始时立即全部执行,然后再发生任何其他事情。每个命令只是告诉赛普拉斯在未来做某事。如果你想将你自己的代码按顺序排列到 运行,你可以使用 .then(),像这样:

// ...
cy.get(#full-form-select-game > div > ul').then(elements => {
    const gameMax = elements.length;
    const targetGameIdx = Math.floor(Math.random() * gameMax);
    cy.get('#full-form-select-game > div > ul')[targetGameIdx].click();
});

用这个替换最后三个 Cypress 命令,它应该 可以工作。我还没有测试过它,但它至少应该让你走上正轨。

基本了解 Cypress 的工作原理对于编写 Cypress 测试至关重要。如果您还没有,我强烈建议您阅读文档中精彩的 introduction to Cypress