May 29, 2025

Writing Effective Unit Tests: Best Practices

Master unit testing in JavaScript with Jest. Learn AAA pattern, mocking, isolation, test coverage, edge cases, and TDD with clear, maintainable examples.

Author

Nilesh KumarSoftware Engineer - II
Writing Effective Unit Tests: Best Practices

If you have ever stared at a failing test and wondered, "What is this even testing?", you're not alone.

Passing tests is only part of the story. Truly effective unit tests are readable, maintainable, and meaningful. In this post, we'll break down what makes a good unit test and how to write them well using Jest.

Why Unit Tests Matter

Before diving into the how, let’s talk about the why:

  • Catch bugs early: Finding issues during development is significantly cheaper than post-release.
  • Enable safe refactoring: Good tests give you confidence to change code without unintended breakage.
  • Serve as documentation: Tests explain how your code should behave.
  • Improve team collaboration: New developers understand code faster by reading tests.
  • Save money: A Microsoft study showed proper testing can reduce bug-related costs by 30–50%.

In fact, teams with strong testing practices ship features up to 30% faster, thanks to less debugging and smoother maintenance.

What You’ll Learn

  • AAA pattern (Arrange, Act, Assert)
  • Test isolation & avoiding test pollution
  • Proper mocking of dependencies
  • Handling edge cases & error conditions
  • Writing maintainable, readable tests
  • Coverage metrics & goals
  • Intro to TDD (Test-Driven Development)
  • Jest-powered examples throughout

The AAA Pattern: Arrange, Act, Assert

A simple, structured way to write readable tests:

  1. Arrange: Set up test data and environment
  2. Act: Invoke the code under test
  3. Assert: Verify the result

Example with Jest

// calculator.ts
export function add(a: number, b: number): number {
  return a + b;
}
// calculator.test.ts
describe('add()', () => {
  it('adds two numbers', () => {
    // Arrange
    const a = 2;
    const b = 3;

    // Act
    const result = add(a, b);

    // Assert
    expect(result).toBe(5);
  });
});

This structure makes the test intent crystal clear.

Test Isolation & Avoiding Pollution

Each test must be independent. Shared state, side-effects, or flaky setups lead to brittle tests.

Problematic Example

let counter = 0;

it('increments once', () => {
  counter++;
  expect(counter).toBe(1); // might pass
});

it('increments again', () => {
  counter++;
  expect(counter).toBe(1); // fails if previous test ran
});

Fix with Isolation

let counter: number;

beforeEach(() => {
  counter = 0;
});

Pro Tip: Avoid relying on external databases, files, or services in unit tests.

Mocking Dependencies

Mocks help you isolate the unit under test by simulating external behavior.

Types of Test Doubles

Type

Use Case

Mock

Expect certain calls or behavior

Stub

Provide canned responses

Spy

Observe calls without changing behavior

Fake

Lightweight implementation (e.g. in-memory DB)

Dummy

Placeholder not actually used in the test

Example: Jest Mocking

// userService.ts
import { db } from './db';

export async function getUserName(userId: string) {
  const user = await db.findUser(userId);
  return user?.name;
}
// userService.test.ts
jest.mock('./db');
import * as db from './db';
import { getUserName } from './userService';

it('returns user name', async () => {
  (db.findUser as jest.Mock).mockResolvedValue({ name: 'Alice' });
  const name = await getUserName('123');
  expect(name).toBe('Alice');
});

Don’t overuse mocks—they can create false confidence and tie tests to implementation details.

Testing Edge Cases & Errors

Most bugs live in edge cases. Cover them.

Boundary Values

it('applies discount at $100', () => {
  expect(calculateDiscount(100)).toBe(10);
});

Error Handling

it('throws when dividing by zero', () => {
  expect(() => divideNumbers(10, 0)).toThrow('Cannot divide by zero');
});

Unexpected Inputs

it('returns error on malformed JSON', () => {
  expect(parseUserInput('{bad json}')).toEqual({ valid: false, reason: 'invalid format' });
});

Testing Async Code

it('resolves user data', async () => {
  global.fetch = jest.fn().mockResolvedValue({
    json: () => Promise.resolve({ id: 1, name: 'John' })
  });

  const result = await fetchUserData(1);
  expect(result).toEqual({ id: 1, name: 'John' });
});

Testing Side Effects

beforeEach(() => {
  jest.spyOn(console, 'log').mockImplementation(() => {});
});

afterEach(() => {
  jest.restoreAllMocks();
});

it('logs message', () => {
  logger.log('Test');
  expect(console.log).toHaveBeenCalledWith(expect.stringContaining('Test'));
});

Test Coverage

Types of Coverage

  • Line: Was each line executed?
  • Branch: Were all if/else paths run?
  • Function: Were all functions invoked?

Tips

  • Don’t chase 100%
  • Focus on critical logic, not trivial code

bash


jest --coverage

Writing Maintainable Tests

Readable tests = maintainable tests.

Guidelines

  • Descriptive test names
  • Use describe blocks for organization
  • Avoid duplication with helpers/factories
function createProduct(overrides = {}) {
  return { id: 'p1', name: 'Item', price: 10, ...overrides };
}

Embracing TDD: Red, Green, Refactor

  1. Red: Write a failing test
  2. Green: Make it pass with minimal code
  3. Refactor: Clean the implementation

Example

test('adds two numbers from string input', () => {
  const calc = new StringCalculator();
  expect(calc.add('1,2')).toBe(3);
});

TDD improves design, encourages modularity, and builds a natural test suite.

Bonus Tips

  • Use beforeEach/afterEach wisely
  •  Keep tests focused (one test = one behavior)
  • Don’t assert unrelated outcomes in one test
  • Use snapshot testing sparingly
  • Run in watch mode (jest-- watch)
  • Use pre-commit hooks to enforce testing discipline
  • Prioritize clarity over cleverness

Final Thoughts

Well-written unit tests are a long-term investment—they accelerate development, reduce bugs, and improve code quality.

Stick to principles like the AAA pattern, proper mocking, isolation, and meaningful naming. And always remember:

Test code is production code—treat it with the same care.

What’s your biggest challenge with writing unit tests? Drop a comment—I’d love to hear your thoughts!

Subscribe to Our Newsletter

RELATED ARTICLES

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari

Aug 19, 2026

The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari
A real-world look at how oversized images can trigger Safari reloads and iOS crashes in Flutter apps and how smarter image decoding prevents them.
From Prompting to Process: What Changed When Flutter Shipped Agent Skills

Aug 19, 2026

From Prompting to Process: What Changed When Flutter Shipped Agent Skills
This blog explores how Flutter Agent Skills improve AI-assisted development by combining official framework workflows with project-specific guidance for more consistent development.
Why Everything Your AI Builds Looks the Same

Aug 19, 2026

Why Everything Your AI Builds Looks the Same
This blog explores why AI-generated interfaces often look alike and explains how design systems, product context, and reusable engineering practices help teams build distinctive, scalable
How We Built the Missing Bridge from Code to Figma
Technology

Jul 10, 2026

How We Built the Missing Bridge from Code to Figma
This blog explores how AI-generated React apps get turned into fully editable, designer-ready Figma files by reading React Fiber instead of the DOM.
Building a Resilient Hybrid-Cloud Network with WireGuard HA, Route-Based Failover, and Deep Observability
Technology

Jun 27, 2026

Building a Resilient Hybrid-Cloud Network with WireGuard HA, Route-Based Failover, and Deep Observability
A practical breakdown of building resilient AWS-to-on-premises connectivity with WireGuard HA, active-standby failover, and deep packet-forwarding observability.
We Built a 114-Second AWS-to-Azure Failover. Here’s What We Learned
Technology

Jun 19, 2026

We Built a 114-Second AWS-to-Azure Failover. Here’s What We Learned
A practical guide to building a 114-second multi-cloud disaster recovery failover between AWS and Azure — what we built, what broke, and what we learned.
Cloud-Native and Cloud-Agnostic Are Not Ideologies; They Are Business-Stage Decisions
Technology

Jun 12, 2026

Cloud-Native and Cloud-Agnostic Are Not Ideologies; They Are Business-Stage Decisions
This blog explains how organizations can balance speed, scalability, and operational flexibility as they grow from startup to enterprise scale.

The Right Conversation Can Save You Six Months.

Whether you’re navigating AI adoption, modernizing legacy systems, or scaling a product - we start by listening. No pitch deck. No template. A real conversation.

Effective Unit Testing with Jest: Best Practices & Examples - GeekyAnts