Error Testing in JavaScript

Test error handling

IntermediateError 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}

Output

Error test: true

What's going on

Error testing ensures proper handling.

Error Throwing Tests

Verify errors thrown
Check error messages
Validate error types

Error Type Tests

instanceof checks
Error names
Custom error types

Mock Scenarios

Network errors
Timeout errors
Validation errors
Various failures

Assertion Helpers

Check error thrown
Verify error type
Test error handling

Async Error Tests

Promise rejections
Async/await errors
Error propagation

Integration Tests

Multiple scenarios
Error boundaries
Recovery logic

Best Practices

Test all error paths
Mock error scenarios
Verify error handling
Test recovery