This course is no longer being maintained. We recommend the testing section of the Intermediate React course instead. We now recommend you take the Intermediate React, v5 course.

Check out a free preview of the full Testing React Applications, v2 course:
The "react-testing-library Exercise" Lesson is part of the full, Testing React Applications, v2 course featured in this preview video. Here's what you'd learn in this lesson:

In this exercise, students use react-testing-library to render and simulate top-level methods and getByText and getByLabelText test selector methods.

Get Unlimited Access Now

Transcript from the "react-testing-library Exercise" Lesson

>> Kent C. Dodds: Just a couple more and then I'll set you free. So simulate is actually built into ReactDOM, so this is just a re-export from ReactDOM. And you could check out the docs there. It's pretty straightforward. Simulate whatever event you want, the element you wanna simulate it on, and then any extra data that you want to simulate that on.

[00:00:22] In our integration test, we're gonna click on a link that's a React router link. In React router, make sure that you're doing a left click. And so you have to add extra event data, so that you can inform React router that it's actually a left click. And I have an example of that, but that's a use case for that event data.

[00:00:43] Wait accepts a callback. You can also pass some options for how quick your interval should be. Cuz it's just checking every x number of seconds and running your callback, waiting for it to not throw an error. And then, also timeout. The default is like 4,500 milliseconds because Jest will time out after 5,000 milliseconds.

[00:01:06] You can also do this, well, yeah. There's also a utility in DOM testing library, which I don't think is exposed from React testing library yet. But it's waitForElement, and with this, you can actually say wait for element. And it will give you back the element that you're waiting for, which is pretty handy dandy.

[00:01:36] So you can check that out later if you want to. Okay, and we'll look at the fireEvent later. All right, you ready to refactor your test to use this stuff? Give it a try at least. You could install Enzyme if you really want to, and feel free to do that.

[00:01:55] And then you'll have to be like, I have to install an adaptor too. And like but have fun with that if you want to. So where we're gonna be working is login.step-2.todo. And I've got some things that you can just comment out and make some changes and stuff.

[00:02:17] Just play around with it a little bit. I think we'll just do this for five minutes. It should be pretty quick, and then we'll come back and we'll work though the solution. So you're in watch mode, you hit p, log in.step.2.todo, and that all get your login step 2 test running.