Jest - hdknr/gatsby-home GitHub Wiki
Add Jest
This recipe helps you setup Jest in your Gatsby site to test components and utilities
Step 1 / 3
Installing the jest package
Proposed changes
NPMPackage:
* Install jest@latest
✅ Installed NPM package [email protected]
Step 2 / 3
Adding some jest test files for you to play with
Proposed changes
File:
* Write src/jest-example/sum.js
---
- Original - 0
+ Modified + 4
+ function sum(a, b) {
+ return a + b;
+ }
+ module.exports = sum;
---
File:
* Write src/jest-example/sum.test.js
---
- Original - 0
+ Modified + 4
+ const sum = require('./sum');
+ test('adds 1 + 2 to equal 3', () => {
+ expect(sum(1, 2)).toBe(3);
+ });
---
Step 2
Adding some jest test files for you to play with
✅ Wrote file src/jest-example/sum.js
✅ Wrote file src/jest-example/sum.test.js
Step 3 / 3
Adding a test & test:watch scripts to your package.json.
Now Try running npm run test — jest will run your test!
While writing tests you can run npm run test:watch and tests will re-run as you edit them.
Proposed changes
NPMScript:
* Add new command to your package.json
---
- Original - 1
+ Modified + 1
@@ -53,7 +53,7 @@
"format": "prettier --write
\"**/*.{js,jsx,ts,tsx,json,md}\"",
"serve": "gatsby serve",
"start": "npm run develop",
- "test": "echo \"Write tests! ->
https://gatsby.dev/unit-testing\" && exit 1",
+ "test": "jest",
},
"version": "0.1.0",
}
---
NPMScript:
* Add new command to your package.json
---
- Original - 0
+ Modified + 1
@@ -54,6 +54,7 @@
"serve": "gatsby serve",
"start": "npm run develop",
"test": "echo \"Write tests! ->
https://gatsby.dev/unit-testing\" && exit 1",
+ "test:watch": "jest --watch",
},
"version": "0.1.0",
}
---
Step 3
Adding a test & test:watch scripts to your package.json.
Now Try running npm run test — jest will run your test!
While writing tests you can run npm run test:watch and tests will re-run as you edit them.
✅ Wrote script test to your package.json
✅ Wrote script test:watch to your package.json
---
The recipe finished successfully!
✅ Installed NPM package [email protected]
✅ Wrote file src/jest-example/sum.js
✅ Wrote file src/jest-example/sum.test.js
✅ Wrote script test to your package.json
✅ Wrote script test:watch to your package.json
Test
% gatsby clean; npm run test
info Deleting .cache, public
info Successfully deleted directories
> [email protected] test /Users/hdknr/Documents/Dropbox/Projects/sample/gatsby-home
> jest
PASS src/jest-example/sum.test.js
✓ adds 1 + 2 to equal 3 (2 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.834 s, estimated 1 s
Ran all test suites.