From 5fb29bd5cc5fa44aa7af39f7797e44a148b4013c Mon Sep 17 00:00:00 2001 From: Gpx Date: Tue, 23 Oct 2018 19:43:24 +0200 Subject: [PATCH] =?UTF-8?q?docs:=20=E2=9C=8F=EF=B8=8F=20explain=20how=20to?= =?UTF-8?q?=20implement=20custo=20getByTestId?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/README.md b/README.md index 34265fea..195d2ad6 100644 --- a/README.md +++ b/README.md @@ -557,6 +557,47 @@ const usernameInputElement = getByTestId('username-input') > about `data-testid`s from the blog post ["Making your UI tests resilient to > change"][data-testid-blog-post] +
+ What if my project already uses data-test-id? Do I have to migrate to data-testid? + + +`getByTestId` is looking for the `data-testid` attribute and that's not going to +change +[#76](https://github.com/kentcdodds/dom-testing-library/issues/76#issuecomment-406321122) +[#128](https://github.com/kentcdodds/dom-testing-library/issues/128) +[#204](https://github.com/kentcdodds/react-testing-library/issues/204). + +What you can do is to create a [custom render](#custom-render) that overwrites +`getByTestId`: + +```js +// test-utils.js +import {render} from 'react-testing-library' + +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 + }, + } +} + +// re-export everything +export * from 'react-testing-library' + +// override render method +export {customRender as render} +``` + +
+ #### `asFragment(): DocumentFragment` Returns a `DocumentFragment` of your rendered component. This can be useful if