当 cypress 的 DOM 中不存在元素时显示错误消息

jai*_*ikl 6 cypress

当元素不存在时,我如何使用 cypress 显示自定义错误消息?

对于下面的代码片段,我想显示:“没有显示行”而不是提供的;“预计 #rows 存在于 DOM 中”。

cy.get('#rows').should('exist');
Run Code Online (Sandbox Code Playgroud)

Ric*_*sen 2

Cypress 事件处理提供了一个可用于自定义错误消息的钩子。

Cypress 日志显示格式错误${error.name}:${error.message}。您可以更改这两个错误属性,但它们:是硬编码的。

这是一些样本,

describe('custom error', () => {

  // Ref: https://docs.cypress.io/api/events/catalog-of-events.html#Catching-Test-Failures
  it('fails with custom error message', () => {
    cy.on('fail', (error, runnable) => {
      error.name = 'CustomError'
      error.message = 'Incorrect, 1 !== 2'
      throw error // throw error to have test still fail
    })
    cy.wrap(1).should('eq', 2)
  })


  /*
    Ref: https://docs.cypress.io/api/cypress-api/custom-commands.html#Child-Commands
    Add this to /cypress/support/commands.js
  */
  Cypress.Commands.add('onFail', { prevSubject: true }, (chainedSubject, message) => {
    cy.on('fail', (error, runnable) => {
      error.name = 'CustomError'
      error.message = 'Incorrect, 1 !== 2'
      throw error // throw error to have test still fail
    })
    return chainedSubject
  })

  it('fails with custom message via command', () => {
    cy.wrap(1).onFail(customError).should('eq', 2)
  })


  /*
    Ref: https://docs.cypress.io/api/cypress-api/custom-commands.html#Overwrite-Existing-Commands
    Add this to /cypress/support/commands.js
  */
  Cypress.Commands.overwrite('should', (originalFn, actual, assertion, expected, options) => {
    if (options && options.message) {
      cy.on('fail', (error, runnable) => {
        error.name = 'CustomError'
        error.message = options.message
        throw error // throw error to have test still fail
      })
    }
    return originalFn(actual, assertion, expected, options)
  })

  it.only('fails with custom message via overwrite of should', () => {
    cy.wrap(1).should('eq', 2, { message: 'Incorrect: 1 !== 2'})
  })


  it('fails with standard message', () => {
    cy.wrap(1).should('eq', 2)
  })
})
Run Code Online (Sandbox Code Playgroud)

它还适用于cy.get()

此测试使用 acy.get()并且它还发出自定义消息

it('fails with a custom message when using cy.get()', () => {
  cy.visit('https://docs.cypress.io/api/commands/get.html')
  cy.get('h1').onFail('Failed to find this text').should('contain', 'NoSuchText')    
})
Run Code Online (Sandbox Code Playgroud)