Course contentsShow
← React
Lesson 2137 of 2,39647. Testing Patterns and Best PracticesFree lesson

Using console.error Mocks to Silence Expected Errors

Mock console.error before tests that throw errors to prevent noise in test output while still verifying functionality.

Using console.error Mocks to Silence Expected Errors

You'll learn how to mock console.error to prevent React's intentional error messages from cluttering your test output when testing error boundaries or expected failures.

The Problem: Noisy Test Output

When you test error boundaries or components that intentionally throw errors, React logs warnings and error messages to the console. While these errors are expected and part of your test scenario, they pollute your test output, making it harder to spot actual test failures.

Think of it like testing a smoke alarm: you want the alarm to go off during your test, but you don't need to hear the loud siren every time you verify it works. You just need confirmation that it triggered.

Silencing Expected Errors

Before running a test that throws an error, mock console.error to prevent output:

import { vi, beforeEach, afterEach } from 'vitest';

beforeEach(() => {
  // Silence console.error for this test
  vi.spyOn(console, 'error').mockImplementation(() => {});
});

afterEach(() => {
  // Restore original behavior
  vi.restoreAllMocks();
});

test('error boundary catches errors', () => {
  // Test code that throws errors
  // No console noise in output
});

The mock intercepts console.error calls and does nothing with them, keeping your test output clean. After the test, vi.restoreAllMocks() restores normal console behavior.

Why This Matters

Clean test output helps you quickly identify real problems. When every test run shows red error text, developers become desensitized to errors—like a car alarm that everyone ignores. By silencing expected errors, unexpected failures stand out clearly.

Key Takeaway: Mock console.error before tests that intentionally throw errors to keep test output clean while still verifying error-handling functionality works correctly.