Skip to content

Commit e87afb4

Browse files
committed
Add a description explaning unit test that handles intialization errors
1 parent a5b3105 commit e87afb4

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

src/metrics/DiagnosticsMetrics.test.ts

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,37 @@ describe('DiagnosticsMetrics', () => {
7070
expect(recordedHistogramCalls[0].value).toBe(100)
7171
})
7272

73+
/**
74+
* @description
75+
* Verifies that DiagnosticsMetrics handles metric client initialization failures gracefully
76+
* without crashing the application.
77+
*
78+
* Test Strategy:
79+
* 1. Configure getMetricClient() mock to reject before instance creation
80+
* - This simulates diagnostics service being unavailable
81+
* - Must be done BEFORE constructor runs since it immediately calls getMetricClient()
82+
*
83+
* 2. Create DiagnosticsMetrics instance
84+
* - Constructor calls initMetricClient() synchronously
85+
* - initMetricClient() starts async initialization (returns immediately)
86+
* - Async code races getMetricClient() vs timeout
87+
* - getMetricClient() rejects due to our mock
88+
* - catch block logs error and sets metricsClient = undefined
89+
*
90+
* 3. Wait for async initialization to complete
91+
* - Constructor returns immediately (can't await in constructor)
92+
* - Need to wait for async promise to settle before checking results
93+
* - 10ms is sufficient for promise rejection and catch block execution
94+
*
95+
* 4. Verify graceful degradation
96+
* - Instance was created successfully (no exception thrown)
97+
* - Error was logged to console (operational visibility)
98+
* - metricsClient remains undefined (all record methods will no-op)
99+
* */
73100
it('should handle initialization errors gracefully', async () => {
101+
102+
// Mock the getMetricClient (which is a Jest mock) to return an error
103+
// Using mockRejectedValueOnce to configure the mock to reject with an error the next time it's called
74104
const error = new Error('Initialization failed')
75105
;(getMetricClient as jest.Mock).mockRejectedValueOnce(error)
76106

@@ -79,9 +109,10 @@ describe('DiagnosticsMetrics', () => {
79109
// Create new instance that will fail initialization
80110
const failingMetrics = new DiagnosticsMetrics()
81111

82-
// Wait for initialization attempt
112+
// Wait for initialization attempt (async operation in constructor)
83113
await new Promise(resolve => setTimeout(resolve, 10))
84114

115+
// Verify error was logged (provides operational visibility)
85116
expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to initialize metric client:', error)
86117

87118
consoleErrorSpy.mockRestore()

0 commit comments

Comments
 (0)