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
- You may not write production code until you have written a failing unit test.
- You may not write more of a unit test than is sufficient to fail, and not compiling is failing.
- 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
:
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', () => {
})
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 />)
})
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:
Now we need to make it fail. Let's ask it to find the title:
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)
})
With this we'll get an output similar to this:
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>
</>
)
}
Now once we save the file, our testing terminal should re-run the test, you should see an output similar to this:
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!
Top comments (0)