07 / Journal / Mobile App Development

Efficient Unit Testing with Jest for Gatsby, TypeScript, and React Testing Library

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…

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 jestbabel-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 jestand 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

 

  • #jest
  • #react
  • #Typescript
  • #unit test
Share

Comments

No comments yet. Start the conversation.

Leave a comment

Comments are moderated. Privacy policy.

01 / Read next

Related writingand work.

TypeScript

Building Real-Time Web applications with tRPC: A Comprehensive Guide

In today's digital world, real-time web applications have become increasingly popular, enabling users to experience instant updates and seamless interactions. One powerful tool that developers can leverage to build real-time web apps is tRPC. With tRPC, developers can create fully type-safe APIs using TypeScript, Next.js, Chakra UI, and Prisma ORM. This comprehensive guide will walk…

Data Science

Empowering Tomorrow: Unleashing the Potential of Big Data Solutions

In the vast digital landscape of today's interconnected world, data has become more than just a commodity - it is the lifeblood that fuels innovation, drives decision-making, and shapes the future of industries. At the forefront of this data-driven revolution stands the formidable arsenal of Big Data Solutions, a powerful suite of technologies and methodologies…

Mobile App Development

Innovating the Future: Unveiling Cloud App Development Strategies

In the rapidly evolving landscape of technology, the fusion of data science and software engineering propels us into uncharted territories. As a seasoned data scientist and software engineer, my professional journey unfolds not merely as a pursuit of excellence but as a relentless exploration of innovation. This journey is not just about technological advancement; it's…

Live product
Agentic AI · LLMOps

JourneyMeshMulti-Agent AI Travel Planner LangGraph + MCP + LLMOps

Supervisor-routed multi-agent travel planning with guardrails, evaluation and human review

  • Python
  • LangGraph
  • LangChain
  • MCP
  • +8

Discuss this idea

Working on somethinglike this?

If Efficient Unit Testing with Jest for Gatsby, TypeScript, and React Testing Library touches a problem you have, tell me about it - I’m happy to compare notes or scope the work.

Let’s chat