DEV Community

Kent C. Dodds
Kent C. Dodds

Posted on

What do you think of React Testing Library?

I wrote React Testing Library about a year and a half ago because I was teaching testing workshops and I wasn't happy with enzyme. I felt like there was so much I had to tell people to not use in enzyme (like the API was some kind of mine field). So I created React Testing Library and I've been very happy with it.

I'd love to hear what others think. And have you had a chance to use any other members of the Testing Library Family, like DOM Testing Library, Cypress Testing Library, Vue Testing Library, etc? I'd love to hear your thoughts on that too!

Top comments (71)

Collapse
 
bdbchgg profile image
bdbch

Happy to see you over here at dev.to! :) To be honest I'm still very unexperienced with testing. Should I do it with a test project first to get into it?

(Also a cool feature for dev.to would be to mark specific posts as discussions, I'd like to use dev.to as my blog on my website).

Collapse
 
kenbellows profile image
Ken Bellows • Edited

The #discuss tag is just for that!

#discuss

What color should the bike shed be?
Collapse
 
jacobmgevans profile image
Jacob Evans

I agree add #discuss :)

Thread Thread
 
kentcdodds profile image
Kent C. Dodds

Done! Thanks folks!

Thread Thread
 
ben profile image
Ben Halpern

We have some long overdue design improvements on the editor to help people select the right tags, so it's great to see this meta discussion help folks out.

Kent, between this and your other couple posts I think you're making really great use of the format of the site and look forward to more of this community-enabling content; using your de facto leadership role in JS/React to spark a lot of great discussions that have a bit more lasting value than a Twitter thread.

👏👏👏

Thread Thread
 
jacobmgevans profile image
Jacob Evans

Ben...what do you think about react testing library lmao

Collapse
 
bdbchgg profile image
bdbch

Yep, see here:
dev.to/bdbch/comment/d8mn

Collapse
 
acostalima profile image
André Costa Lima • Edited

I believe the #discuss tag is normally used for that. 😉

Collapse
 
bdbchgg profile image
bdbch

Can you exclude this tag when you want to fetch it via the articles endpoint?

I'd like to integrate dev.to into my website instead of medium but wouldn't like to see my discussion posts in there. :)

Sure could filter out on my side, but that would break the pagination.

Thread Thread
 
acostalima profile image
André Costa Lima

Not sure. I haven't used the API yet. Maybe the docs can provide you a hint. 👌

Thread Thread
 
kenbellows profile image
Ken Bellows • Edited

@bdbch if you're just trying to page through your own articles, you can probably just pull in the whole dang list and do whatever sorting and paging you want on the client. You'd have to write a ton of articles for that to be a problem. Different story if you're pulling more that just your own, but in that case you'll probably have a more specific query anyway

Thread Thread
 
bdbchgg profile image
bdbch

Thats true, guess thats the best way to go from here on! :)

Collapse
 
kentcdodds profile image
Kent C. Dodds

Should I do it with a test project first to get into it?

You could do that if you like. I think you'll find that it's pretty easy to get up and going though. You can even try it in the very same file that you're using enzyme in as well! So migrating is a pretty simple process.

Collapse
 
shaik_ameem profile image
Ameem Shaik • Edited

Overall I think it's great and solves many of the issues with enzyme.

My favorite parts are:

  1. It prevents you from accessing the instance. This is the most common testing mistake I see in the code bases I work on-- calling .instance() and then directly invoking an internal method for testing.

  2. It prevents you from querying by the component name, e.g. expect(wrapper.find(MyComponent)).toEqual(...). This is especially an issue when writing integration tests with enzyme, as the component structure is really just an implementation detail at that point. I think static rendering (render()) might be a better option, but most people just seem to use mount. In any case, that leads to my next point:

  3. Much smaller, simpler API. Enzyme provides so much functionality that it can be really hard to figure out the right approach for a given situation. Even worse is that much of the functionality can lead to really brittle tests. There's just a lot less decision making with RTL.

Collapse
 
2ezpz2plzme profile image
Steven Liao

RTL doesn't prevent you from accessing the instance since it's still possible to get the instance by

const ref = React.createRef();
const testUtils = render(<ClassComponent ref={ref} />;
const instance = ref.current;

The fact that RTL does not provide an instance() API certainly does discourage accessing the instance though, and I agree with that. I also agree with all your parts.

Collapse
 
shaik_ameem profile image
Ameem Shaik

True, "prevent" was probably the wrong word to use here!

Thread Thread
 
kentcdodds profile image
Kent C. Dodds

I use the word "enable"

Collapse
 
kentcdodds profile image
Kent C. Dodds

I'll start. I love it! It enables me to write tests that resemble the way my software is used which gives me more confidence and makes tests easier to write (and read). I only need to change my tests when I actually change my app's behavior, and my tests actually help me catch bugs. Also, the fact that I don't have to change my tests as I refactor to hooks (and it handles the act() calls for me) is fantastic.

Collapse
 
jacobmgevans profile image
Jacob Evans

Super awesome to see you posting on dev.to!!!! :)

Collapse
 
evanstern profile image
Evan Stern

We picked up React Testing Library when we made the jump to React Hooks and were looking for a testing platform that supported it (enzyme did not). In the process we found that with RTL we could write better integration style tests with fewer test files and better code coverage.

Personally, I love the ideology behind RTL. Forcing your tests to interact with the DOM the way your users will makes the tests far more robust and descriptive and promotes much more expressive UI design.

As a side note, I love the updates that I have been seeing to RTL and the surrounding libraries. Great job!

Collapse
 
kentcdodds profile image
Kent C. Dodds

I love the ideology behind RTL...

I love the updates...

That's great to hear!

I think a lot of people jumped on with the hooks thing. Enzyme now supports hooks (mostly anyway), but I think people are discovering that react testing library is a better way to test components anyway.

Inertia is hard to beat, so it will be a very long time before RTL has more downloads than enzyme, but I do believe it will happen eventually.

Collapse
 
2ezpz2plzme profile image
Steven Liao • Edited

I've been using RTL personally and love it so far. The ideology behind it makes so much sense.

However, I have to use Enzyme at work and it makes following the idea behind RTL so much harder. Finding elements with Enzyme returns a bunch of implementation details that don't usually don't really help.

I had tried to convince the frontend architect at my company to switch over to RTL for testing. He had tried it but didn't like it for a couple of reasons:

  • There is no shallow rendering (I believe he loves unit testing components). He believes that each component and test should be isolated from one another, so that tests would not bleed into one another, making tests less brittle than rendering the entire tree.
  • Rendering the entire tree with RTL makes it really ez to have huge, unmaintainable tests. I told him it is possible to unit test with RTL, but he said the fact that the default is full DOM rendering just makes it to ez to not unit test.

I had argued that shallow rendering does not give the confidence that the code works, but he said there needs to be a balance for maintainability. I proposed adding RTL to the codebase to allow everyone to try it out but he argued that when a developer encounters a test in RTL, the developer would have to learn a whole different set of testing API to make changes to the test.

I honestly still think RTL makes the better trade-off though because I followed its ideology in Enzyme and it has actually caught bugs for me.

Collapse
 
kentcdodds profile image
Kent C. Dodds

I should write about this. People who complain that tests break a lot when testing this way don't understand that they're breaking for the right reasons whereas testing implemention details makes your tests break for the wrong reasons. Ugh.

Collapse
 
2ezpz2plzme profile image
Steven Liao • Edited

:/ Ever since I learned about the RTL ideology, using Enzyme has just been pretty miserable for me. It's so ez to test an implementation detail, find elements that also return the Component element rather than just the DOM element.

At work, I mostly see shallow rendering, expecting this shallow wrapper to match snapshot, expecting wrapper.state('whatever') to equal something... Don't really wanna start any crap so I try not to say anything.

Also, I can't seem to find another reliable way in Enzyme to wait for an async componentDidMount besides returning the promise inside componentDidMount and awaiting. I don't really like this approach though... because it relies on implementation detail.

// something.tsx
componentDidMount() {
  return promise
}

// something.test.tsx
await wrapper.instance().componentDidMount()
wrapper.update()
expect(...)...

The frontend architect at my company endorses this pattern. So I'm pretty much forced to use this pattern since I can't use RTL waitForElement.

Btw, looking forward to your talk at useReactNYC on Tuesday.

Thread Thread
 
kentcdodds profile image
Kent C. Dodds

Sweet! Let me know who you are! Looking forward to meeting you.

Collapse
 
shaik_ameem profile image
Ameem Shaik

Have you tried using Jest mocks to replicate shallow rendering? If not, maybe try suggesting this approach to your architect. See FAQ for more info.

Using Jest mocks is actually a more powerful approach anyways, since it allows you to explicitly choose which components to mock. With shallow, all components are mocked, even if they're defined in the same file.

Collapse
 
2ezpz2plzme profile image
Steven Liao

Yep. His concern was that it's too ez to not mock and then developers would put a bunch of tests into the component higher up in the tree, making it harder to maintain, whereas when shallow rendering just mocks as much as possible, encouraging to test whatever the current component does.

Collapse
 
kcvgan profile image
kcvgan

So far so good. I had one case however where I was unable to figure out one test case.
I have a button, that button has text. Upon clicking the button, the text gets replaced by a spinner. Thing is, the width of the button should stay the way it was when text was inside and not squeeze to be spinner sized. I did a simple render, put the width of the component in a variable and then fired a click event. I then tried getting the width and seeing if it matched. It was 0 all the time. I’m a bit new to testing but assumed JSDom or JestDom is being used when I render() the component and it would simulate properly. I even tried wrapping the button in a container div with preset dimensions. No luck still. For other unit tests it was a breeze. It really made me rethink how I test my Frontend.

Collapse
 
acostalima profile image
André Costa Lima

I think JSDOM only provides DOM APIs. It isn't a full-blown rendering engine which is required to determine element's visual and structural properties. You'd have to use some visual testing tool to validate the behavior you described.

Collapse
 
kcvgan profile image
kcvgan

That’s what I concluded after tests but really wanted to test this case programmatically. I guess visual testing it has to be then.

Thread Thread
 
thatzacdavis profile image
Zachary Davis

You could check the styles or classes being applied at least and trust that the CSS is doing it's thing.

Thread Thread
 
kentcdodds profile image
Kent C. Dodds

Yep, that's what I'd recommend. You could also use the style prop and verify the node.style.width is correct.

Thread Thread
 
kcvgan profile image
kcvgan

Thanks, will try!

Thread Thread
 
acostalima profile image
André Costa Lima

Would that really work in this case, i.e., when width is not specified by a CSS class?

Thread Thread
 
kentcdodds profile image
Kent C. Dodds

With JSDOM, you can't measure layout, but you can verify that the style/class name was applied and trust that in the browser's ability to lay it out properly based on that.

Thread Thread
 
acostalima profile image
André Costa Lima

Got it! Thanks! 😄

Collapse
 
jacobmgevans profile image
Jacob Evans

I love it! I constantly trying to push the library and thinking paradigm on everyone.

At the very least at my work, since they are still going to use Enzyme, I constantly am encouraging people to learn and research the paradigm (philosophy) that you have written about and the entire react-testing-library is built around... Ever since then, I have become the "go-to guy" for unit testing questions, I also have now done a few internal pieces of training. The tests have significantly improved, the coverage has increased and people have a better idea of WHY they are creating the tests just from shifting that mindset alone!

Collapse
 
robertcaldecott profile image
Robert Caldecott 🇬🇧

I love it and so does my team. I was an early adopter and introduced it to the team as an alternative approach to ReactTestUtils/snapshots. Testing components and workflows from the user's POV gives us enormous confidence and the ability to find elements using a11y tags kills two birds with one stone. We use it in conjunction with jest-dom and are over the moon with how reliable the products are.

The only real testing pain we've encountered has been lack of async act support but React 16.9 will fix this and we found plenty of useful workarounds thanks to conversations on the @testing-library/react GitHub page.

So thank you Kent and all the project contributors. Long live @testing-library!

Collapse
 
dbrudner profile image
dbrudner • Edited

It's the shit. My coworkers and I love it. I think enzyme, frankly, is weird as fuck (wtf is shallow rendering and what does .dive do? I don't get it).

Everything about react testing library so far has been really awesome. Easy to set up, easy to use, encourages testing UI the right way, and is just generally dope af. Much respect.

Collapse
 
shermayster profile image
Pavel Shermayster

Love it

I wrote tests for almost two years with jasmine and karma for Angular project.

Now I'm working with react, react testing library and wallabyjs and tests is not pain anymore. For me it was huge improvements in my workflow and I feel much more productive.