Skip to content

Commit 556dbf6

Browse files
committed
docs: ✏️ explain how to implement custo getByTestId
1 parent fe3b65c commit 556dbf6

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,47 @@ const usernameInputElement = getByTestId('username-input')
557557
> about `data-testid`s from the blog post ["Making your UI tests resilient to
558558
> change"][data-testid-blog-post]
559559
560+
<details>
561+
<summary>What if my project already uses <code>data-test-id</code> do I have to migrate to <code>data-testid</code>?
562+
</summary>
563+
564+
`getByTestId` is looking for the `data-testid` attribute and that's not going to
565+
change
566+
[#76](https://github.com/kentcdodds/dom-testing-library/issues/76#issuecomment-406321122)
567+
[#128](https://github.com/kentcdodds/dom-testing-library/issues/128)
568+
[#204](https://github.com/kentcdodds/react-testing-library/issues/204).
569+
570+
What you can do is to create a [custom render](#custom-render) that overwrites
571+
`getByTestId`:
572+
573+
```js
574+
// test-utils.js
575+
import {render} from 'react-testing-library'
576+
577+
const customRender = (node, ...options) => {
578+
const utils = render(node, ...options)
579+
580+
return {
581+
...utils,
582+
getByTestId: id => {
583+
const el = utils.container.querySelector(`[data-test-id="${id}"]`)
584+
if (!el) {
585+
throw Error(`Unable to find an element by: [data-test-id="${id}"]`)
586+
}
587+
return el
588+
},
589+
}
590+
}
591+
592+
// re-export everything
593+
export * from 'react-testing-library'
594+
595+
// override render method
596+
export {customRender as render}
597+
```
598+
599+
</details>
600+
560601
#### `asFragment(): DocumentFragment`
561602
562603
Returns a `DocumentFragment` of your rendered component. This can be useful if

0 commit comments

Comments
 (0)