How I Closed a Major DevOps Gap: Adding Jest Unit Testing to My Clinic Project

On Day 18 of my DevOps Challenge, my lecturer reviewed my DevOps toolchain and introduced 11 important steps to consider when building a more reliable application delivery process.

One point immediately caught my attention: my clinic project had no automated tests in its CI/CD pipeline.

My clinic application was already live. I had configured GitHub Pages for hosting and connected my custom domain through Namecheap. However, I had not yet introduced automated tests to check whether important parts of the application were working before deployment.

That meant I could make a change, push it to GitHub, and deploy a broken component without an automated test catching the problem first.

I decided to address this gap on Day 19.

In this post, I'll document how I approached unit testing with Jest and React Testing Library, how I connected testing to GitHub Actions, and how I tested the deployment gate to see whether a failed test would prevent a new deployment.

This was another step in my journey from simply deploying applications to learning how to deliver changes more safely.

Why I Needed Automated Tests

My clinic project was already accessible online, but having a working website did not mean every change I made would be safe.

Consider a simple example.

Suppose I change the appointment form and accidentally remove the patient name field's required validation. The website might still load normally, but users could submit incomplete appointment information.

Without automated tests, I might not discover the problem until I tested the form manually or a user encountered it.

This is where automated testing becomes useful.

The DevOps principle of shift left encourages teams to identify problems earlier in the software delivery process rather than waiting until an application reaches production.

Before this improvement, my deployment process did not include an automated testing stage.

My goal was straightforward:

  • Write tests for important parts of my clinic application.
  • Run the tests automatically through GitHub Actions.
  • Allow deployment only when the tests pass.
  • Introduce a basic safety check before new code reaches my live website.

This was not about making my project perfect in one day. It was about identifying a weakness and taking a practical step to address it.

Step 1: Installing Jest and React Testing Library

My clinic project uses React with Vite.

I chose Jest for unit testing and React Testing Library for testing components from the user's perspective.

Jest provides the testing framework, while React Testing Library helps render components and interact with them in tests.

I opened my VS Code terminal inside the project directory and installed the development dependencies:

npm install --save-dev jest @testing-library/react @testing-library/jest-dom @testing-library/user-event jest-environment-jsdom

The packages serve different purposes:

  • Jest: Runs the tests and evaluates assertions.
  • React Testing Library: Renders React components so their behavior can be tested.
  • jest-dom: Adds useful DOM assertions, such as checking whether an element is visible or required.
  • user-event: Supports realistic interactions such as typing and clicking.
  • jest-environment-jsdom: Provides a simulated browser environment for DOM-based tests.

An important configuration detail

Because my application uses Vite, Jest needs additional configuration to handle the project's JavaScript modules, JSX, and any Vite-specific imports.

Installing the packages alone is not always enough.

A Jest configuration might include:

module.exports = {
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
};

This configuration tells Jest to use a simulated browser environment and load a setup file before running tests.

However, the exact configuration depends on the project's module system and how React components are transformed. For example, projects using ES modules and JSX may need Babel or another compatible transformation setup.

I also needed to ensure that my package.json contained the appropriate test script.

A typical script entry is:

{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "test": "jest"
  }
}

Important: Add these entries to your existing scripts object rather than replacing the entire package.json. Your project may contain other scripts that are still needed.

Once the configuration was in place, I could move on to writing tests for the application.

Step 2: Writing Tests for the Appointment Form

I wanted to begin with an important part of the clinic application: the appointment form.

Rather than writing tests that only checked whether the application loaded, I focused on a few specific behaviors:

  • Whether the appointment form displayed its heading.
  • Whether the patient name field was required.
  • Whether the phone number field was required.
  • Whether the user could enter a name.
  • Whether the service selection field was available.

I created a test file under the component's test directory.

For example:

src/components/__tests__/AppointmentForm.test.jsx

The exact path depends on your project's existing directory structure.

Here is an illustrative version of the test:

import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import userEvent from '@testing-library/user-event';

import AppointmentForm from '../AppointmentForm';

describe('Clinic Appointment Form', () => {
  test('renders the appointment heading', () => {
    render(<AppointmentForm />);
    expect(
      screen.getByText(/Book Appointment/i)
    ).toBeInTheDocument();
  });

  test('requires the patient name', () => {
    render(<AppointmentForm />);
    const nameInput = screen.getByPlaceholderText(
      /Enter Patient Name/i
    );
    expect(nameInput).toBeRequired();
  });

  test('requires a phone number', () => {
    render(<AppointmentForm />);
    const phoneInput = screen.getByPlaceholderText(
      /Phone Number/i
    );
    expect(phoneInput).toBeRequired();
    expect(phoneInput).toHaveAttribute('type', 'tel');
  });

  test('allows a user to enter a patient name', async () => {
    const user = userEvent.setup();
    render(<AppointmentForm />);
    const nameInput = screen.getByPlaceholderText(
      /Enter Patient Name/i
    );
    await user.type(nameInput, 'Victor John');
    expect(nameInput).toHaveValue('Victor John');
  });

  test('displays the clinic service selection field', () => {
    render(<AppointmentForm />);
    expect(
      screen.getByLabelText(/Select Service/i)
    ).toBeInTheDocument();
  });
});

What do these tests actually verify?

Each test checks a specific behavior. Test 1 checks heading, Test 2 checks patient name required attribute, Test 3 checks phone field, Test 4 simulates typing, Test 5 checks service dropdown. These are useful starting tests, but they do not cover every possible booking scenario. Further tests could verify validation errors and submission handling. The selectors must match your actual component labels.

Running the tests

npm test

My reported result was five passing tests. Seeing those passing tests gave me confidence that the specific behaviors I had tested were working. It was a useful reminder that successful deployment and successful testing are two different things.

Step 3: Integrating Jest with GitHub Actions

Writing tests locally was a good start, but I wanted GitHub Actions to run them automatically whenever I pushed changes or opened a pull request targeting the main branch.

Before this improvement, my workflow focused on building and deploying the application. I wanted to introduce a testing stage before deployment.

The key idea was to create two jobs: A test job that installs dependencies and runs tests, and a deploy job that builds and publishes only after testing succeeds.

The GitHub Actions workflow could look like this:

File: .github/workflows/deploy.yml

name: Clinic CI/CD Pipeline

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  test:
    name: Run Jest Unit Tests
    runs-on: ubuntu-latest
    steps:
      - name: Check out repository
        uses: actions/checkout@v4
      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm
      - name: Install dependencies
        run: npm ci
      - name: Run tests with coverage
        run: npm test -- --coverage

  deploy:
    name: Build and Deploy Clinic
    needs: test
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Check out repository
        uses: actions/checkout@v4
      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm
      - name: Install dependencies
        run: npm ci
      - name: Build React application
        run: npm run build
      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./dist

Important: This is an example workflow. Before using it, confirm that Jest is correctly configured, that npm ci works with your lockfile, and that your existing GitHub Pages setup supports deployment through peaceiris/actions-gh-pages.

Understanding the most important line

needs: test

This establishes a dependency. GitHub Actions must complete the test job successfully before the deploy job can run. If tests fail, deployment is skipped. This creates a basic testing gate in the CI/CD pipeline: Code change → Install → Test → Build → Deploy. If testing fails, pipeline stops before deployment.

Step 4: Understanding Test Coverage

During my testing, I reported seeing approximately 78% coverage. Coverage measures how much code was executed during tests. A report might show Statements, Branches, Functions, Lines. These percentages are not interchangeable. 78% does not mean 78% bug-free, it tells how much code was exercised.

The workflow generates a coverage report with npm test -- --coverage but generating a report is not enforcing a threshold. If you want to require minimum coverage, configure a threshold in Jest:

module.exports = {
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
  collectCoverageFrom: [
    'src/**/*.{js,jsx}',
    '!src/main.jsx',
  ],
  coverageThreshold: {
    global: {
      statements: 70,
      branches: 60,
      functions: 70,
      lines: 70,
    },
  },
};

Step 5: Testing Whether the Deployment Gate Works

A workflow file can look correct without behaving as expected, so I verified its behavior. My goal was to confirm deployment runs after tests pass, and does not run if tests fail. I deliberately changed text expected by a test so assertion no longer matched.

Expected behavior:

  • All tests pass → Test job Passes → Deploy Runs on push to main
  • A test fails → Test job Fails → Deploy Skipped
  • Pull request → Test Runs → Deploy Skipped

After failed test, previously deployed version remains available because new deployment did not run. Workflow prevents new deployment when tests fail, but does not automatically roll back earlier deployment.

Lessons I Learned as a DevOps Beginner

1. Successful deployment does not guarantee working functionality - I had learned to deploy my clinic at sirvickcloud9.online, but not to check behavior. Testing helped address that.

2. Start with important user journeys - Beginning with appointment form gave practical way to learn unit testing.

3. A CI/CD pipeline should do more than deploy - The needs: test dependency was simple but important improvement because it connected testing and deployment.

4. Coverage is useful, but not whole story - High coverage does not automatically mean effective tests. Tests should check meaningful behavior.

5. DevOps improvement is continuous process - Five passing tests is not enough to guarantee production-ready. They are beginning of disciplined testing.

Conclusion

On Day 19 of my  DevOps Challenge, I addressed an important gap in my clinic project's delivery process. I introduced Jest unit testing, began testing the appointment form, and worked on integrating automated tests into GitHub Actions.

The most important lesson was not simply learning a new testing tool. It was understanding that deploying an application and delivering changes safely are two different responsibilities.

Hosting gets an application online. Automated testing helps check whether important parts of it behave as expected before new changes are deployed.

My journey began with learning how to deploy applications. I am now learning how to introduce checks that make those deployments more reliable.

Tomorrow is Day 20, the final day of my 20 Days DevOps Challenge. I plan to review the lessons from my lecturer's 11-step DevOps toolchain and examine the improvements I have made throughout this learning journey.

Next: My Final DevOps Toolchain Audit — What I Improved and What I Still Need to Learn.


Read Also:  My Lecturer's DevOps Toolchain 11 Steps Audit           https://blog.sirvickcloud9.online/2026/10/lecturer-devops-toolchain-11-steps-audit.html

Comments

Popular posts from this blog

How I Fixed GitHub Error: failed to push some refs to github.com in 2026

How I Deployed Netflix Clone (NGold) to AWS EC2 - Live at 32.196.145.76:3000 [Docker + Nginx Guide]

Understanding Linux Environment — The Real Engine Behind My AWS Cloud Deployment