Skip to content

Testing implementation instead of behavior

Quick summary

Your test checks how the code works internally rather than what it does — refactoring breaks the test even if behavior is unchanged.

Why this happens

  • The test asserts on internal function calls, private methods, or state

  • The test checks the number of times an internal function is called rather than the output

  • The test depends on the specific algorithm or data structure used internally

Minimal example

✗ Broken code
test('sorts users', () => {
  const spy = jest.spyOn(Array.prototype, 'sort');
  getSortedUsers();
  expect(spy).toHaveBeenCalled(); // tests implementation — breaks if algorithm changes
});
✓ Fixed code
test('sorts users', () => {
  const users = getSortedUsers();
  for (let i = 1; i < users.length; i++) {
    expect(users[i].name >= users[i - 1].name).toBe(true); // tests behavior
  }
});

Testing that the output is sorted rather than which sorting algorithm is used makes the test robust to refactoring.

How to diagnose

  • Review the test to see if it asserts on public API output or internal implementation

  • Try refactoring the implementation without changing behavior — if tests break, they test implementation

  • Check if the test accesses private methods or internal state directly

How to fix

  • Rewrite the test to assert on public behavior: inputs and outputs, not internal calls

  • Remove assertions on internal function call counts unless they are part of the contract

  • Test the observable effect: return values, side effects, and state changes

How to prevent

  • Focus tests on public API behavior — what the function returns and its observable effects

  • Avoid testing private methods or internal state; test through the public interface

Related Resources

Related Lessons

← Back to language