Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Error Testing in JavaScript

Test error handling in JavaScript: check that code throws, check the error type, mock failures, test async errors and many scenarios. Explanation and output.

IntermediateJavaScript Error HandlingExample 10 of 10
error-testing.js
1// Method 1: Test error throwing
2function testErrorThrowing() {
3 try {
4 throw new Error('Test error');
5 return false; // Should not reach here
6 } catch (error) {
7 return error.message === 'Test error';
8 }
9}
10
11console.log('Error test:', testErrorThrowing());
12
13// Method 2: Test error types
14function testErrorType() {
15 try {
16 throw new TypeError('Type error');
17 } catch (error) {
18 return error instanceof TypeError;
19 }
20}
21
22// Method 3: Mock error scenarios
23function createErrorScenario(type) {
24 switch (type) {
25 case 'network':
26 throw new Error('Network error');
27 case 'timeout':
28 throw new Error('Timeout');
29 case 'validation':
30 throw new ValidationError('Invalid input');
31 default:
32 throw new Error('Unknown error');
33 }
34}
35
36// Method 4: Error assertion helper
37function assertError(fn, expectedError) {
38 try {
39 fn();
40 return false; // Should have thrown
41 } catch (error) {
42 if (expectedError) {
43 return error instanceof expectedError;
44 }
45 return true; // Any error is fine
46 }
47}
48
49assertError(() => {
50 throw new TypeError('Type error');
51}, TypeError);
52
53// Method 5: Async error testing
54async function testAsyncError() {
55 try {
56 await Promise.reject(new Error('Async error'));
57 return false;
58 } catch (error) {
59 return error.message === 'Async error';
60 }
61}
62
63// Method 6: Error boundary testing
64function testErrorBoundary(errorBoundary, errorFn) {
65 try {
66 errorFn();
67 } catch (error) {
68 errorBoundary.catchError(error, { component: 'TestComponent' });
69 }
70 return errorBoundary.getErrors().length > 0;
71}
72
73// Method 7: Integration error testing
74async function testErrorHandling() {
75 const scenarios = [
76 () => { throw new Error('Error 1'); },
77 () => { throw new TypeError('Error 2'); },
78 () => { throw new ReferenceError('Error 3'); }
79 ];
80
81 const results = scenarios.map(scenario => {
82 try {
83 scenario();
84 return { passed: false };
85 } catch (error) {
86 return { passed: true, error: error.name };
87 }
88 });
89
90 return results;
91}

Sample Output

Error test: true

In this one

  • How to test that a function throws
  • How to check the error type in a test
  • What a mock error scenario is
  • How to test errors in async code

How it works

  1. 1

    testErrorThrowing throws Test error.

  2. 2

    catch compares the message and returns true.

  3. 3

    console.log prints Error test: true.

  4. 4

    assertError runs but its result is not printed.

  5. 5

    The other tests are only defined.

Edge cases

Function does not throw

A try-only test passes even when no error happens.

Return false or fail after the call, as assertError does.

Undefined error class

new ValidationError throws a ReferenceError.

Define or import the class first.

Async test without await

The test ends before the promise rejects.

Await the promise or return it from the test.

What's going on

Error handling is code too, so it needs tests. A test is a small piece of code that runs your code and checks the result. Error tests make sure the right error is thrown, with the right type, at the right time. This JavaScript sample shows the ideas without a test library.

Method 1 throws an error inside try and checks the message in catch. It returns true when the message matches, and the program prints Error test: true. The return false after throw never runs, because throw jumps straight to catch.

Method 2 checks the type with instanceof. That matters when callers handle TypeError and RangeError in different ways.

Method 3 builds fake error scenarios, called mocks. A mock is a stand-in for real behaviour, so you can test network or timeout errors without a real network. Note that ValidationError is not defined in this sample. The 'validation' case would throw a ReferenceError instead. Define the class, as in the Custom Errors page, before using it.

Method 4, assertError, runs a function and returns true only if it threw the expected error. If the function does not throw, the test fails, which catches a missing check in your code. Its result is not printed here.

Method 5 tests an async function with await inside try. Method 6 checks that an error boundary recorded the error. Method 7 runs several scenarios and returns a list of results with each error name.

Only Method 1 prints. In real projects, tools like Jest give you expect(fn).toThrow(TypeError) for the same job.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does assertError return if fn does not throw?

Pick an answer to check it.

Question 2

What happens to "return false" right after a throw?

Pick an answer to check it.

Questions people ask

Do I need a test library?

Not to learn. Libraries like Jest add clear reports and helpers like toThrow.

What should an error test check?

That it throws, the error type, and the message or code.

Why test error paths at all?

They run rarely, so bugs in them hide until a real failure.