Course contentsShow
← JavaScript
Lesson 2682 of 2,72354. Testing in JavaScriptFree lesson

Assertion Error Messages

Writing descriptive test failures by understanding default and custom messages.

Assertion Error Messages

You'll learn how to write test failures that actually tell you what went wrong — instantly.

The Problem: Silent or Cryptic Failures

When a test fails, the default error message might just say "Expected true to equal false" or show two complex objects that differ somewhere. You're left squinting at output, mentally tracing which assertion failed and why it matters.

Understanding Default Messages

Most assertion libraries provide decent default messages:

expect(user.age).toBe(18); // "Expected 25 to be 18"

That's helpful, but it doesn't explain why we expected 18 or what user represents in this test context.

Writing Custom Descriptive Messages

Modern assertion libraries let you add context as an optional final argument or through chaining:

// Node's assert module
assert.strictEqual(user.age, 18, 'New user should start at legal adult age');

// Jest/Vitest style - no built-in message param, but error shows context
expect(user.age).toBe(18); // Rely on good test/variable naming

// Or wrap with descriptive test names
it('should initialize new users at age 18 for legal compliance', () => {
  expect(user.age).toBe(18);
});

The Analogy: Breadcrumbs vs Maps

Default messages are breadcrumbs — they tell you where you fell. Custom messages are maps — they explain the terrain and why that spot mattered.

Best Practices

  • Use descriptive test names — often better than message strings
  • Add custom messages when the assertion's business logic isn't obvious
  • Include actual context: which user, which iteration, what scenario
  • Don't just repeat the assertion in English

Key Takeaway: Great error messages transform debugging from detective work into instant diagnosis — invest in clarity when defaults fall short.