liveBook · Manning

Expectation

As explained in The Art of Unit Testing 3e

An expectation is the behavior or result that a test predicts for a specified unit and scenario.

An expectation is the behavior or result a test predicts for a particular unit and scenario. A useful test name states the unit under test, its inputs or scenario, and the expected behavior—the USE pattern. section 2.5.3

Keep expectations useful and readable by following a few practical rules:

  • Name the unit, scenario, and expected result clearly so a failed build points toward the production-code problem. section 2.5.3
  • Keep expectations close to the mock they configure; local setup makes behavior and intent easier to follow than a large shared setup. section 9.4
  • Avoid piling up interaction checks: excessive expectations can make tests fragile and obscure the important behavior. section 5.6.5
  • Prefer stubs for supplying values or exceptions, and reserve mocks for interactions that genuinely matter to the scenario. section 5.6.5

A precise expectation

A test named “verifyPassword, given a failing rule, returns errors” predicts a specific result: calling verifyPassword with a failing rule produces an error containing the rule’s reason. The expectation is narrow enough to explain the scenario without checking unrelated interactions. section 2.5.3

Listing 2.5 Naming a test with USE
test('verifyPassword, given a failing rule, returns errors', () => {
  const fakeRule = input => ({ passed: false, reason: 'fake reason' });
 
  const errors = verifyPassword('any value', [fakeRule]);
  expect(errors[0]).toContain('fake reason');
});

Browse the complete JavaScript example showing a USE-style test name and an expectation that checks the returned error. section 2.5.3

How The Art of Unit Testing 3e covers it

How deep it goes
Explains expectations through USE naming, local mock setup, readability concerns, and overspecification risks.
Examples
Uses verifyPassword errors, failing password rules, logger calls, mock setup, and received-interaction checks as concrete examples.
What you can do after
Diagnose failures through clearer test names and reduce fragile tests by limiting unnecessary mock expectations.
How it connects
Connects expectations to unit under test, scenarios, test names, mocks, stubs, setup functions, and test readability.

Also explained in

Compare how 5 books explain expectation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Unit Testing 3e. The section links point to the parts of the book it draws on.