Skip to content
Velloreth
Programming 7 min read

Unit Testing Basics: What to Test and How

Unit tests verify one piece of behaviour in isolation. Learn what makes a good test, the arrange-act-assert structure, and common mistakes.

By

What a unit test is

A unit test verifies one small piece of behaviour in isolation. It runs fast, has no external dependencies, and fails for exactly one reason.

function calculateDiscount(subtotal: number, isPremium: boolean): number {
  if (isPremium && subtotal > 100) return subtotal * 0.2;
  return 0;
}

test('gives 20% discount to premium users over 100', () => {
  expect(calculateDiscount(200, true)).toBe(40);
});

The test calls one function with known inputs and asserts the output. No database, no network, no filesystem. It runs in microseconds.

Arrange, act, assert

The standard structure for a test has three parts.

test('applies the discount only above the threshold', () => {
  // Arrange: set up the inputs
  const subtotal = 50;
  const isPremium = true;

  // Act: call the code under test
  const discount = calculateDiscount(subtotal, isPremium);

  // Assert: verify the outcome
  expect(discount).toBe(0);
});

The three sections make the test readable at a glance. A reader sees what was set up, what was called, and what was expected, without reading the implementation.

Some tests need no arrange section — a pure function with literal inputs. That is fine; the structure is a guide, not a ritual.

Test behaviour, not implementation

The most important principle. A test should verify what the code does, not how it does it.

// Bad: tests the implementation
test('calls repository.save once', () => {
  const repo = { save: jest.fn() };
  const service = new UserService(repo);
  service.createUser({ name: 'Ada' });

  expect(repo.save).toHaveBeenCalledTimes(1);
});

This test breaks if you change how persistence works — for example, batching saves. The behaviour did not change, but the test fails.

// Good: tests the behaviour
test('persists the created user', async () => {
  const repo = new InMemoryUserRepository();
  const service = new UserService(repo);

  await service.createUser({ name: 'Ada' });

  const saved = await repo.findByName('Ada');
  expect(saved).not.toBeNull();
});

This test verifies the outcome. It survives a change from one save call to a batched save, because it checks the result rather than the mechanism.

The rule: assert on observable outcomes, not on internal calls. Mock call counts are occasionally necessary, but they should be the exception.

What makes a good test

Fast. A test suite that takes ten minutes will not be run. Unit tests should run in milliseconds each.

Deterministic. The same inputs always produce the same result. No dependence on the clock, random values, or network.

Isolated. Tests do not depend on each other’s state or execution order. Each can run alone.

Readable. The test name describes the behaviour, and the body is easy to follow.

Focused. It fails for one reason, so a failure points directly at the cause.

Edge cases and failure paths

The happy path is the least interesting case. Bugs live in the edges.

describe('calculateDiscount', () => {
  test('gives 20% to premium users over 100', () => {
    expect(calculateDiscount(200, true)).toBe(40);
  });

  test('gives nothing to non-premium users', () => {
    expect(calculateDiscount(200, false)).toBe(0);
  });

  test('gives nothing at exactly the threshold', () => {
    expect(calculateDiscount(100, true)).toBe(0);
  });

  test('gives nothing below the threshold', () => {
    expect(calculateDiscount(99, true)).toBe(0);
  });

  test('handles zero', () => {
    expect(calculateDiscount(0, true)).toBe(0);
  });
});

The boundary case — exactly 100 — is where off-by-one bugs appear. Testing it explicitly is worth the line.

Other cases to cover:

  • Empty collections.
  • Null and undefined.
  • Negative numbers.
  • Very large numbers.
  • Duplicate values.
  • Unicode and special characters in strings.

Testing code with dependencies

Code with side effects needs the dependency injected so it can be replaced.

interface Clock {
  now(): Date;
}

class SubscriptionService {
  constructor(private clock: Clock) {}

  isExpired(expiresAt: Date): boolean {
    return this.clock.now() > expiresAt;
  }
}

// Test with a fixed clock
test('reports an expired subscription', () => {
  const clock = { now: () => new Date('2026-01-01') };
  const service = new SubscriptionService(clock);

  expect(service.isExpired(new Date('2025-12-31'))).toBe(true);
});

The clock is injected, so the test controls time. Without injection, the test would depend on the real clock and be non-deterministic.

This is the practical payoff of dependency inversion: testable code.

Test names

A test name should describe the behaviour and the condition, so a failure tells you what broke.

// Bad
test('test1', () => { });
test('works', () => { });

// Good
test('returns 0 when the cart is empty', () => { });
test('throws when the email is invalid', () => { });
test('applies the discount when the user is premium', () => { });

The pattern is what it does + under what condition. A failing test named returns 0 when the cart is empty tells you exactly what regressed.

Common mistakes

Testing implementation details. Asserting on internal calls makes tests brittle.

One giant test. A test that checks ten things fails for ten possible reasons. Split it.

Shared mutable state. Tests that depend on each other’s state fail in unpredictable orders.

Testing the framework. Asserting that the ORM saves a row tests the ORM, not your code.

No assertions. A test that calls code and asserts nothing always passes.

Assertions that cannot fail. expect(result).toBeDefined() passes for almost anything.

Slow tests. A test that sleeps for a second to wait for a timeout makes the suite unusable.

Ignoring flaky tests. A test that fails intermittently gets disabled, and then it protects nothing. Fix it or delete it.

Organising tests

As a suite grows, organisation matters as much as the individual tests.

Group by unit, not by type. A file of tests for calculateDiscount is easier to navigate than a file of “all the tests that happen to be about numbers”. Co-locate the test file with the source file, or mirror the source tree.

Use describe blocks for the unit and the method. Nesting by behaviour keeps related cases together and makes the output readable when something fails.

describe('Cart', () => {
  describe('add', () => {
    test('adds an item to an empty cart', () => { });
    test('increments quantity for a duplicate item', () => { });
  });

  describe('remove', () => {
    test('removes the last item without throwing', () => { });
    test('does nothing for an item that is not present', () => { });
  });
});

Use a factory for test data. Building objects inline in every test means a new required field breaks dozens of tests. A factory with defaults fixes that.

function makeUser(overrides: Partial<User> = {}): User {
  return {
    id: 'test-id',
    email: 'test@example.com',
    name: 'Test User',
    ...overrides,
  };
}

test('rejects a user with no email', () => {
  const user = makeUser({ email: '' });
  expect(() => validateUser(user)).toThrow();
});

Only the field under test is specified; everything else has a sensible default. This is the single highest-value habit for keeping a suite maintainable.

Keep setup in beforeEach, not at the top of the file. Shared mutable state at module scope is the most common cause of order-dependent tests.

Practical guidance

  • Test one behaviour per test, so a failure points at one cause.
  • Use arrange, act, assert for readability.
  • Assert on outcomes, not on internal calls.
  • Cover edge cases and failure paths, not just the happy path.
  • Inject dependencies so tests can control time, randomness, and I/O.
  • Name tests after behaviour and condition.
  • Keep tests fast and deterministic — slow or flaky tests get disabled.
  • Test through the public API, not private methods.

For the related practices, see test-driven development guide and mocking and stubbing. For the broader context, why your tests are slow and refactoring basics.

Quotable summary

A unit test verifies one piece of behaviour in isolation, runs fast, and fails for exactly one reason. Arrange, act, assert is the standard structure: set up the state, perform the action, verify the outcome. Test behaviour rather than implementation, so the tests survive refactoring — assert on observable outcomes, not on internal call counts. A good test is fast, deterministic, isolated, readable, and focused. Cover the edge cases and failure paths, not just the happy path, because that is where bugs live, and pay particular attention to boundary values where off-by-one errors appear. Inject dependencies so tests can control time, randomness, and I/O, which is the practical payoff of dependency inversion.

Frequently asked questions

What is a unit test?
A unit test verifies one small piece of behaviour in isolation, usually a single function or method. It runs fast, has no external dependencies, and fails for exactly one reason.
What is the arrange-act-assert pattern?
It is the standard test structure: arrange the inputs and state, act by calling the code under test, then assert the expected outcome. The three sections make the test readable at a glance.
How many assertions should a test have?
One logical assertion is the guideline. Several assertions are fine if they verify the same behaviour, but if a test checks unrelated things, it should be split so a failure points at one cause.
Should I test private methods?
Usually not directly. Test them through the public API. If a private method is complex enough to need its own tests, that is a signal it should be extracted into a separate, testable unit.
What is the difference between a unit test and an integration test?
A unit test isolates one piece of code with no external dependencies. An integration test exercises several pieces together, including real databases, APIs, or file systems, to verify they work in combination.
How do I test code with side effects?
Inject the dependency so you can substitute a fake. If a function writes to a database, take the database as a parameter and pass an in-memory implementation in the test.