From 2b694cc091c6bdbce8819c03f7e571e136a23076 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Fri, 31 Jan 2025 18:13:24 +0100 Subject: [PATCH] fix: do not throw unhandled exception when data is undefined in interceptor.reply --- lib/mock/mock-utils.js | 4 +++- test/mock-interceptor.js | 40 ++++++++++++++++++++++++++++++++++++++++ test/mock-utils.js | 6 ++++++ 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/lib/mock/mock-utils.js b/lib/mock/mock-utils.js index b19aaaf8e11..cce9f818c84 100644 --- a/lib/mock/mock-utils.js +++ b/lib/mock/mock-utils.js @@ -124,8 +124,10 @@ function getResponseData (data) { return data } else if (typeof data === 'object') { return JSON.stringify(data) - } else { + } else if (data) { return data.toString() + } else { + return '' } } diff --git a/test/mock-interceptor.js b/test/mock-interceptor.js index 7b17efe1a6e..09b3b13c5a6 100644 --- a/test/mock-interceptor.js +++ b/test/mock-interceptor.js @@ -107,6 +107,46 @@ describe('MockInterceptor - reply options callback', () => { }) }) + test('should handle undefined data', t => { + t = tspl(t, { plan: 2 }) + + const mockInterceptor = new MockInterceptor({ + path: '', + method: '' + }, []) + const result = mockInterceptor.reply((options) => ({ + statusCode: 200, + data: undefined + })) + t.ok(result instanceof MockScope) + + // Test parameters + + const baseUrl = 'http://localhost:9999' + const mockAgent = new MockAgent() + after(() => mockAgent.close()) + + const mockPool = mockAgent.get(baseUrl) + + mockPool.intercept({ + path: '/test', + method: 'GET' + }).reply((options) => { + t.deepStrictEqual(options, { path: '/test', method: 'GET', headers: { foo: 'bar' } }) + return { statusCode: 200, data: 'hello' } + }) + + mockPool.dispatch({ + path: '/test', + method: 'GET', + headers: { foo: 'bar' } + }, { + onHeaders: () => { }, + onData: () => { }, + onComplete: () => { } + }) + }) + test('should error if passed options invalid', async (t) => { t = tspl(t, { plan: 4 }) diff --git a/test/mock-utils.js b/test/mock-utils.js index b80db2a401c..2d0044b60dc 100644 --- a/test/mock-utils.js +++ b/test/mock-utils.js @@ -174,6 +174,12 @@ describe('getResponseData', () => { const responseData = getResponseData(new TextEncoder().encode('{"test":true}').buffer) t.ok(responseData instanceof ArrayBuffer) }) + + test('it should handle undefined', (t) => { + t = tspl(t, { plan: 1 }) + const responseData = getResponseData(undefined) + t.strictEqual(responseData, '') + }) }) test('getStatusText', (t) => {