If you inspect the package.json file that is generated by the Gatsby blog starter, you’ll find that there’s already an NPM script available known as test
—but it simply outputs an error message, as you can see in the following example:
//
package.json
"scripts":
{
"build":
"gatsby build",
"develop":
"gatsby develop",
"format":
"prettier --write \"**/*.{js,jsx,ts,tsx,json,md}\"",
"start":
"npm run develop",
"serve":
"gatsby serve",
"clean":
"gatsby clean",
"test":
"echo \"Write tests! ->
&& exit 1"
}
To ensure that this NPM script instead runs Jest unit tests that you’ve created, you need to modify the string associated with the test
key to jest
, as follows:
//
package.json
"scripts"
:
{
"build"
:
"gatsby build"
,
"develop"
:
"gatsby develop"
,
"format"
:
"prettier --write \"**/*.{js,jsx,ts,tsx,json,md}\""
,
"start"
:
"npm run develop"
,
"serve"
:
"gatsby serve"
,
"clean"
:
"gatsby clean"
,
"test"
:
"jest"
}
Now, you can run all your Jest unit tests by executing the following command in your terminal:
$
npm
test
To run unit tests together with a flag that enables a watch mode, which tracks changes to files and runs another regimen of unit tests when changes are detected in those files, use this command:
$
npm
test
--
--watch
When you run a round of unit tests successfully, you will see a notice in your terminal about snapshots being created, and alongside your __tests__ directory, a __snapshots__ directory will appear containing JSON representations of each component you tested (in our case, the <Bio />
and <Header />
components).
To have a convenient means of comparing snapshots against one another, you can check your __snapshots__ directory into your source repository so you don’t publish any new code changes without verifying that the snapshots match the intended result. An additional advantage of tracking your snapshots in source control is that you have a record of how your units of functionality have evolved over time.
To update the initial snapshot so new changes aren’t considered regressions, you can run another round of tests and instruct Jest to update the original snapshot to the new state:
$
npm
test
--
-u
Though these unit tests are powerful for verifying that your snapshots match the expected rendered output, what about situations in which you need to do more involved checking to ensure that the DOM of your components matches the rendered output? For this, you can use a tool such as @testing-library/react
, which enables you to write both unit and integration tests for React components (which all Gatsby components are, in the end).
NOTE
If you’re using a continuous integration (CI) system that runs tests for you, like CircleCI or Travis, those systems typically require snapshots to be checked into source control.
Leave a Reply