mgrubinger / blog

https://www.grooovinger.com/
MIT License
0 stars 0 forks source link

Cypress Testing Library Custom Error Message #2

Open mgrubinger opened 1 year ago

mgrubinger commented 1 year ago

date: '2021-06-23T22:00:00Z' short: How to reduce logging noise when using Cypress Testing Library tags:

Cypress Testing Library outputs a rather verbose log message when it can't find an element using e.g. findByRole. The intention is to help you, the developer to fix the test and figure out which accessible elements are available.

However, I find this not very useful and too verbose, especially in a CI environment.

Luckily, Cypress Testing Library allows for customization of the message.

I use this configuration to limit the log messag length, while still keeping the relevant information about which element was not found:

// file: cypress/support/commands.js
import '@testing-library/cypress/add-commands';
import { configure } from '@testing-library/cypress'

configure({
  getElementError: (message, container) => {

    // truncate everything after 'Here are the accessible roles:'
    let indexOfRoleListMessage = message.indexOf('Here are the accessible roles:');
    let shortMessage = message.substring(0, indexOfRoleListMessage);

    // return a new error with the shorter message
    let error = new Error(shortMessage);
    error.name = 'AccessibleElementNotFoundError';
    return error;
  }
})
mgrubinger commented 1 year ago

this is a comment, just to try if this works.