Instructor: This messageViewer component uses the email consumer. It expect to be rendered inside an email context. Let's see how we can test this. First, we'll yarn add react-testing-library. Then we can run yarn test to start up our test watcher.
Then our project will create an tests directory underneath source. Inside there, we'll create a messageViewer.test.js file. In here, we'll import react, because we're going to be using JSX, and import render and fireEvent from react-testing-library.
We'll also want to import emailContext from email-context. This'll be the full context object, not just the provider. Then we'll import messageViewer, which is the component we're testing. Let's write a test for when we're viewing this email.
We should see the subject in the header, and this body in the div. We'll write a test, view an email, then we'll call render, and render out an emailContext.provider, with a messageViewer inside. Into this provider, we'll pass a value prop, setting currentEmail to some fake email, which we'll create up top.
We have to give it a subject and a body. We'll destructure this render call to pull out the container. Then we can write our assertions. We can expect the container.querySelector on the h2 and the textContent from that. This should equal email.subject.
Save this, and we get an error, because the path to messageViewer's wrong. Fix that, and now, our test is passing. Then we can write another assertion for the body. We'll expect container.querySelector h2 plus div.
The div after the h2, and the textContent in there to equal email.body. When we save, the test still passes. Now, let's add another test for the back button. I'll say test backButton, and we're going to need a mock callback function here, which we can create with jest.fn.
Then I'll copy and paste our render from the test above, because this one's going to be really similar. We'll just add a second property to this object, which is onSelectEmail, and pass in our mock callback. Now, we can click the button with fireEvent.click, and pass in container.querySelector button.
After that, we can expect for mock callback to be called with null. Now, we can save, and this test works, too.