Introduction
The core library, DOM Testing Library, is a lightweight solution for querying and interacting with DOM nodes to test web pages. Several frameworks, including React, Angular, and Vue, have been wrapped around the core library to provide ergonomic APIs. There's also a Cypress plugin that uses testing-library queries for end-to-end tests, as well as a React Native implementation. We can also create custom queries using this library!
From this article, we are going to learn how to use custom queries and within method. So let us dive in!
Custom Queries
Many of the helper functions used to implement the default queries are exposed by the DOM Testing Library. The helpers can be used to create custom queries. For example, the code below demonstrates how to use a different data-attribute than the default testId queries.
test-utils.js
const domTestingLib = require('@testing-library/dom')
const {queryHelpers} = domTestingLib
export const queryByTestId = queryHelpers.queryByAttribute.bind(
null,
'data-test-id',
)
export const queryAllByTestId = queryHelpers.queryAllByAttribute.bind(
null,
'data-test-id',
)
export function getAllByTestId(container, id, ...rest) {
const els = queryAllByTestId(container, id, ...rest)
if (!els.length) {
throw queryHelpers.getElementError(
`Unable to find an element by: [data-test-id="${id}"]`,
container,
)
}
return els
}
export function getByTestId(container, id, ...rest) {
// result >= 1
const result = getAllByTestId(container, id, ...rest)
if (result.length > 1) {
throw queryHelpers.getElementError(
`Found multiple elements with the [data-test-id="${id}"]`,
container,
)
}
return result[0]
}
// re-export with overrides
module.exports = {
...domTestingLib,
getByTestId,
getAllByTestId,
queryByTestId,
queryAllByTestId,
}