The task to set up Jest and React Testing library for TDD using Gatsby is an easy one.Its tricky as i planned to use Typescripts in my test.
Firstly , i installed jest
, babel-jest
and babel-preset-gatsby
ensuring the presence of babel preset(s) which can be used internally for Gatsby site.
npm install –save-dev jest babel-jest babel-preset-gatsby identity-obj-proxy tslint-react @types/jest
Configure Jest for checking its working with Gatsby
As Gatsby has its own babel configuration so we have to manually tell jest to use babel-jest. the gatsby website tells to create jest.config.js
file. look at the code below
jest.config.js
const path = require(“path”)
module.exports = {
setupFilesAfterEnv: [
path.resolve(dirname, “./jest-configs/setup-test-env.js”) ], transform: { // “^.+\.(tsx?|jsx?)$”: “ts-jest”, “\.svg”: “/jest-configs/__mocks/svgTransform.js” ,
“^.+\.(tsx?|jsx?)$”: <rootDir>/jest-configs/jest-preprocess.js
,
},
moduleNameMapper: {
// “\.svg”: ./jest-configs/__mocks__/file-mocks.js
,
“\.svg”: <rootDir>/jest-configs/__mocks__/svgTransform.js
,
“typeface-“: “identity-obj-proxy”, “.+\.(css|styl|less|sass|scss)$”: identity-obj-proxy
, “.+\.(jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$”: <rootDir>/jest-configs/__mocks__/file-mocks.js
, }, testPathIgnorePatterns: [node_modules
, .cache
, public
], transformIgnorePatterns: [node_modules/(?!(gatsby)/)
, \\.svg
], globals: { PATH_PREFIX: “, }, testRegex: “(/tests/.|\.(test|spec))\.(ts|tsx)$”,
moduleFileExtensions: [
“ts”,
“tsx”,
“js”
],
collectCoverage: false,
coverageReporters: [
“lcov”,
“text”,
“html”
]
}
svgTransform.js
module.exports = {
process() {
return ‘module.exports = {};’;
},
getCacheKey() {
// The output is always the same.
return ‘svgTransform’;
},
};
The function of transform
option is to tell Jest that all ts, tsx, js or jsx files should be transformed using a jest-preprocess.js file.
jest-configs/jest-preprocess.js
const babelOptions = {
presets: [
‘@babel/preset-react’,
‘babel-preset-gatsby’,
“@babel/preset-typescript”
],
};
module.exports = require(“babel jest”).createTransformer(babelOptions)
some code should also be put in setup-test-env.js
.
The Jest Configuration docs explains the setupFilesAfterEnv: ....
configuration option.
A list of direction or path to modules which run some code to configure or set up the testing framework before each test.
jest-configs/setup-test-env.js
import “@testing-library/jest-dom/extend-expect”
That should have Jest properly configured. Now, I’ll install the testing library and jest-dom as dev-dependencies with npm.
npm install –save-dev @testing-library/react @testing-library/jest-dom
Now run npx jest
and now our code is good to go
SO NOW WE ARE GOOD TO GO
Now i will write my first test and run it. I like TDD because it is fast. We can write test before writing code. A test should fail at the beginning Read this up.
Now i will create a folder named __tests__ in my root folder of project. Then i will create a file named test.spec.tsx and paste this code in it.
tests/test.spec.tsx
import React from "react" import { render } from "@testing-library/react" // You have to write data-testid const Title = () => <h1 data-testid="hero-title">Gatsby is awesome!</h1> test("Displays the correct title", () => { const { getByTestId } = render(<Title />) // Assertion expect(getByTestId("hero-title")).toHaveTextContent("Gatsby is awesome!") // --> Test will pass })
Run commands like Yarn or npm install if you get errors like.
Cannot find module 'react' from 'test.spec.tsx' > 1 | import React from "react"
YAAYYY WE ACCOMPLISHED UNIT TESTING WITH TYPESCRIPT AND GATSBY AND JEST AND REACT TESTING LIBRARY
I am very happy with this . I will just start out Typescript with React so this was a great deal of learning for me. I’ll put up more post about writing real code using TDD. stay tuned
Thanks it really worked !! You saved my day .
Pingback: Building Real-Time Web applications with tRPC: A Comprehensive Guide