Skip to content

Docs: implement data-test-id query using helpers #209

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 23, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 23 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -572,20 +572,35 @@ What you can do is to create a [custom render](#custom-render) that overwrites

```js
// test-utils.js
import {render} from 'react-testing-library'
import {render, queryHelpers} from 'react-testing-library'

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 getElementError(
`Unable to find an element by: [data-test-id="${id}"]`,
container,
)
}
return els
}

export function getByTestId(...args) {
return queryHelpers.firstResultOrNull(getAllByTestId, ...args)
}

const customRender = (node, ...options) => {
const utils = render(node, ...options)

return {
...utils,
getByTestId: id => {
const el = utils.container.querySelector(`[data-test-id="${id}"]`)
if (!el) {
throw Error(`Unable to find an element by: [data-test-id="${id}"]`)
}
return el
},
getByTestId: getByTestId.bind(container),
getAllByTestId: getAllByTestId.bind(container),
queryByTestId: queryByTestId.bind(container),
queryAllByTestId: queryAllByTestId.bind(container),
}
}

Expand Down