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.
1// Method 1: Test error throwing2function testErrorThrowing() {3 try {4 throw new Error('Test error');5 return false; // Should not reach here6 } catch (error) {7 return error.message === 'Test error';8 }9}1011console.log('Error test:', testErrorThrowing());1213// Method 2: Test error types14function testErrorType() {15 try {16 throw new TypeError('Type error');17 } catch (error) {18 return error instanceof TypeError;19 }20}2122// Method 3: Mock error scenarios23function 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}3536// Method 4: Error assertion helper37function assertError(fn, expectedError) {38 try {39 fn();40 return false; // Should have thrown41 } catch (error) {42 if (expectedError) {43 return error instanceof expectedError;44 }45 return true; // Any error is fine46 }47}4849assertError(() => {50 throw new TypeError('Type error');51}, TypeError);5253// Method 5: Async error testing54async 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}6263// Method 6: Error boundary testing64function testErrorBoundary(errorBoundary, errorFn) {65 try {66 errorFn();67 } catch (error) {68 errorBoundary.catchError(error, { component: 'TestComponent' });69 }70 return errorBoundary.getErrors().length > 0;71}7273// Method 7: Integration error testing74async function testErrorHandling() {75 const scenarios = [76 () => { throw new Error('Error 1'); },77 () => { throw new TypeError('Error 2'); },78 () => { throw new ReferenceError('Error 3'); }79 ];8081 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 });8990 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
testErrorThrowing throws Test error.
- 2
catch compares the message and returns true.
- 3
console.log prints Error test: true.
- 4
assertError runs but its result is not printed.
- 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.