Surajan Shrestha

IV

Setup up Jest & React Testing Library with Pre-Commits & CircleCI

Tests that run before every commit, and again in CI.

, on Medium, readytowork publication

6
Jest & React Testing Library with Pre-Commits & CircleCI

Let's set up a Jest & React Testing Library with Pre-Commits (Husky) & CI (CircleCI) for a proper Test Driven Development (TDD).

TDD involves not only writing tests and making sure our application runs as it's expected but also making sure it ships with our CI/CD pipelines & has a good developer experience which can be provided using Pre-commit hooks.

Things we're doing

  1. Part One: Setting up TDD with Pre-Commits (Husky)
  2. Part Two: Setting up TDD with a CI/CD platform (CircleCI)

Tech Stack

  1. Setup tool: Vite with react-ts as a React Typescript template.
  2. Main packages: Jest & React Testing Library
  3. Pre-Commit tool: Husky
  4. CI (Continuous Integration) platform: CircleCI

Folder Structure

-.circleci        <= CI setup using CircleCI
-.husky           <= Pre-Commit setup using Husky
-src
  -components
    -Counter
      -index.tsx
      -Counter.test.tsx   <= Test for Counter Component
    -Link
      -index.tsx
      -Link.test.tsx      <= Test for Link Component
      -__snapshots__      <= Snapshot created by Snapshot test
  -other stuff...
-package.json
-node_modules & other stuff...

1. Part One: Setup TDD with Pre-Commits (Husky)

Pre-commit hooks are special scripts that run in Git before a commit is made. We use such hooks to allow commits to only happen when certain conditions are met. This promotes better code quality and reduces unnecessary commits.

Husky is a go-to tool for handling & setting up pre-commit hooks. This is how it works:

  1. When we try to commit, Husky triggers the pre-commit script.
  2. The pre-commit script runs Jest to execute all our tests.
  3. If all tests pass, the commit proceeds normally.
  4. If any tests fail, Husky prevents the commit, and we'll see error messages detailing the failures.

a. Install Husky

npm install --save-dev husky

b. Initialize Husky

npx husky init

It creates a pre-commit script inside the .husky folder and adds a prepare script to our package.json.

c. Setup test scripts in package.json

"scripts": {
  "test": "react-scripts test",
  "test:staged": "CI=true react-scripts test --o",
  "prepare": "husky"
},

test:staged runs tests in CI mode, which is more suitable to integrate with pre-commit hooks. The --o flag runs tests related with only those files that have changed since last commit.

The essay continues, with the CircleCI setup, on Medium.


First published on Medium in the readytowork publication, 3 April 2024.

7