Jest · Unit tests that survive refactors

How do you structure a Jest test file?

Easytest structuredescribearrange act assertUpdated Oct 2026
Quiz this track

Short answer

Group related cases with describe, declare each case with test, and follow arrange-act-assert. Keep one behaviour per test so a failure points at a single cause.

A readable test file reads top to bottom like a specification. The outer describe names the unit, inner describe blocks name scenarios, and each test states one expected behaviour. Setup should be obvious at the point of use rather than hidden in distant helpers.

ts
describe("applyDiscount", () => {
  describe("when the cart is empty", () => {
    test("returns zero", () => {
      const total = applyDiscount([], 0.1);
      expect(total).toBe(0);
    });
  });

  describe("when a coupon is valid", () => {
    test("subtracts the discount from the subtotal", () => {
      const cart = [{ price: 100 }];
      const total = applyDiscount(cart, 0.1);
      expect(total).toBe(90);
    });
  });
});

The shape of a good case

  • Arrange: build the smallest input that exercises the behaviour
  • Act: call the unit under test exactly once where possible
  • Assert: state the expected outcome with the most specific matcher
  • Avoid sharing mutable objects between cases
  • Let the test name carry the explanation instead of adding narration

One assertion is not a rule, but one behaviour is. A test may check several related outputs from the same action, such as a returned value and a call to a collaborator. It should not verify three unrelated scenarios, because the first failure hides the rest.

Deeply nested describe blocks become hard to scan. Two levels are usually enough; if you need more, the unit probably has too many responsibilities or the file should be split by behaviour.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1How many assertions should a single test contain?
  2. 2When do you split a test file?
  3. 3What belongs in arrange versus a beforeEach hook?
  4. 4Why is one behaviour per test useful?

Say it in the interview

I structure a file around the unit and then around scenarios, using describe for grouping and test for one expected behaviour. Each case follows arrange, act and assert, with the input built locally so the test reads clearly. I keep shared setup small and avoid mutable fixtures across cases. The goal is that a failing test name tells me what broke without opening the implementation.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Jest mock interview and get scored feedback on depth, clarity and confidence.