Definitely yes! You can write unit, integration, and end-to-end tests with this library.
As you write your tests, keep in mind:
The more your tests resemble the way your software is used, the more confidence they can give you. - 17 Feb 2018
This is fairly common. Our first bit of advice is to try to get the default text
used in your tests. That will make everything much easier (more than just using
this utility). If that's not possible, then you're probably best to just stick
data-testids (which is not bad anyway).
Definitely not. That said, a common reason people don't like the
attribute is they're concerned about shipping that to production. I'd suggest
that you probably want some simple E2E tests that run in production on occasion
to make certain that things are working smoothly. In that case the
attributes will be very useful. Even if you don't run these in production, you
may want to run some E2E tests that run on the same code you're about to ship to
production. In that case, the
data-testid attributes will be valuable there as
All that said, if you really don't want to ship
data-testid attributes, then
you can use
this simple babel plugin
to remove them.
If you don't want to use them at all, then you can simply use regular DOM methods and properties to query elements off your container.
const firstLiInDiv = container.querySelector('div li') const allLisInDiv = container.querySelectorAll('div li') const rootElement = container.firstChild
You can make your selector just choose the one you want by including :nth-child in the selector.
const thirdLiInUl = container.querySelector('ul > li:nth-child(3)')
Or you could use
getAllByRole to query the
listitem role and access the
index in question:
const items = [ /* your items */ ] const container = render(/* however you render this stuff */) const thirdItem = getAllByRole(container, 'listitem')
Help! I can't access component methods or the component instance!
This is intentional.
We want you to focus on testing the output and functionality of the component as it is observed by the user and to avoid worrying about the implementation details of the component.
We believe this leads to less brittle and more meaningful test code.
Please refer to the Guiding Principles of this testing library for more info.