赛普拉斯的DOM中不存在元素时显示错误消息

时间:2018-12-12 12:19:22

标签: cypress

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

对于以下代码段,我想显示:“未显示行”,而不是提供的; “预期在DOM中存在#行”。

cy.get('#rows').should('exist');

1 个答案:

答案 0 :(得分:1)

Cypress event handling提供了一个可用于自定义错误消息的钩子。

赛普拉斯日志以${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)
  })
})

它也可以与cy.get()

一起使用

此测试使用cy.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')    
})