When I import screen object like this
import { render, screen } from '@testing-library/react';
it allows me to issue the following command: screen.findByTestId(...)
, but how can I search by data-test
(not data-testid
)? Tried to search by custom attribute, but there was no findByAttribute
method in screen
either.
Have you had a chance to see the the document? https://testing-library.com/docs/dom-testing-library/api-custom-queries/
If you want to query with your own-defined attribute, you can make one using buildQueries
// custom-queries.js
import {queryHelpers, buildQueries} from '@testing-library/react'
// query
const queryAllByData = (...args) =>
queryHelpers.queryAllByAttribute('data-test', ...args)
const [
queryByDataTest,
] = buildQueries(queryAllByData)
export {
queryByDataTest
}
// test-utils.js
import {render, queries} from '@testing-library/react'
import * as customQueries from './custom-queries'
const customRender = (ui, options) =>
render(ui, {queries: {...queries, ...customQueries}, ...options})
// re-export everything
export * from '@testing-library/react'
// override render method
export {customRender as render}
// test.spec.jsx
const {getByData} = render(<Component />)
expect(getByData('my-component')).toHaveTextContent('Hello')
You can find more in the attached document.