Cypress Testing Library Custom Error Message

2021-06-23

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;
  }
})