DEV Community

Sam Preston
Sam Preston

Posted on • Updated on

How to Write Your First React Unit Test

Welcome Back!

Where we left off - GitHub

What we're doing today:

  • Creating a smoke test
  • Performing our first TDD iteration

The Three Laws of Test Driven Development

  1. You may not write production code until you have written a failing unit test.
  2. You may not write more of a unit test than is sufficient to fail, and not compiling is failing.
  3. You may not write more production code than is sufficient to pass the currently failing test.

Creating your first Unit Test

Before we continue where we left off I have created a separate component for the title of the webpage called Title.tsx, I have then added this to a component directory within src:

Title Separation

Now we have everything setup, let's write the test.

We'll start by creating a new testing component called Title.test.js.

For this test we'll be doing something very simple, checking if the title has rendered. This test isn't something you should be doing for every body of text, however, for now it will act as an example for TDD.

test('once rendered title is visible', () => {

})
Enter fullscreen mode Exit fullscreen mode

We'll start by mounting the Title component.

const { render } = require("@testing-library/react")
import Title from './Title'

test('once rendered title is visible', () => {
  render(<Title />)
})
Enter fullscreen mode Exit fullscreen mode

Now to actually run the test, if you have the app already running, open a new terminal and run npm run test. So we currently have an output similar to this:
1st Passing Test

Now we need to make it fail. Let's ask it to find the title:
Title Screenshot
To get what is rendered, we need another import called screen, so we'll use that to find any element on the screen with the text "samuel preston".

const { render, screen } = require("@testing-library/react")
import Title from './Title'

test('once rendered, title is visible', () => {
  render(<Title />)

  screen.getByText(/samuel preston/i)
})
Enter fullscreen mode Exit fullscreen mode

With this we'll get an output similar to this:
1st Failed Test

Now, lets write the code to satisfy this requirement. We'll head back into the Title component and create a new h1 element containing "Samuel Preston".

function Title() {
  return (
    <>
      <h1>
        Samuel Preston
      </h1>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Now once we save the file, our testing terminal should re-run the test, you should see an output similar to this:
1st Iteration Complete

This marks the first iteration of our TDD journey within this project.

GitHub

To view where we're at you can follow this link to the final commit at the end of each post to follow along!

Oldest comments (0)