easyEngineering Practices#71

Jest test — describe/it/expect

Prompt

Write a Jest test suite for a sum function. Test with positive numbers, negative numbers, and zero.

Solution

describe('sum', () => {
  it('adds positive numbers', () => {
    expect(sum(2, 3)).toBe(5)
  })
  it('adds negative numbers', () => {
    expect(sum(-1, -2)).toBe(-3)
  })
  it('adds zero', () => {
    expect(sum(0, 5)).toBe(5)
  })
})
Mentor's take

A test suite's job is to make change cheap: unit tests sit at the bottom of the pyramid because they give the fastest feedback for the lowest cost, and describe/it is where every JavaScript testing conversation starts. The structure matters more than it looks: describe names the unit under test, each it reads as a behavior specification ("it adds negative numbers"), and one assertion concept per it means a failure message tells you exactly which behavior broke — a single it with ten expects fails as one opaque red X.

The describe/it style is BDD's heritage: tests written as readable behavior specs, Given-When-Then compressed into a sentence. Choosing the three cases here (positive, negative, zero) is the actual skill being probed — partitioning the input space instead of testing one happy path three ways.

Stack context worth having ready: Mocha + Chai + Sinon was the composable trio, Jasmine bundled all three, and Jest superseded that generation by shipping runner, assertions, mocking, snapshots, and coverage in one tool.

Red flag: equating BDD with using describe/it syntax. The syntax is only the residue — the practice is behavior-language specs agreed with product before code.

Say it: "Each it is a one-sentence behavior spec over a partition of the input space — positive, negative, zero — so a failure names the exact behavior that regressed."