Writing unit tests

Though a comprehensive accounting of writing Jest tests is outside the scope of this section, let’s write a rudimentary unit test that checks to make sure that our Gatsby blog starter correctly renders the expected <Bio /> component (src/components/bio.js) that is found in the starter.

First, we need to create a new directory within the same directory as our components (src/components) named __tests__. As an alternative, you can place the test file alongside the component in the same directory, with the extension .spec.js or .test.js (a matter of personal preference, since Jest correctly interprets both). In the following example, we place the test file named bio.js in src/components/__tests__:

// src/components/__tests__/bio.js
import React from "react"
import renderer from "react-test-renderer"

import Bio from "../bio"

describe("Bio", () => {
  it("renders correctly", () => {
    const tree = renderer
      .create(<Bio />)
      .toJSON()
    expect(tree).toMatchSnapshot()
  })
})

This test will employ react-test-renderer to render the component, which we import into the test file. Thereafter, it will create a snapshot of the component that reflects its initial state on the first test run. Any future test runs will compare the resulting snapshots with the initial snapshot, allowing for quick detection of deltas that have generated regressions.

You can also use these unit tests in Jest to test components that accept props, such as the header component:

// src/components/__tests__/header.js
import React from "react"
import renderer from "react-test-renderer"

import Header from "../header"

describe("Header", () => {
  it("renders correctly", () => {
    const tree = renderer
      .create(<Header siteTitle="Default Starter" />)
      .toJSON()
    expect(tree).toMatchSnapshot()
  })
})

Writing unit tests will ensure that your code stays pristine and doesn’t introduce any regressions in functionality. But now that you know how to author unit tests in Jest, how can you run them?


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *