Skip to content

Commit 2b694cc

Browse files
fix: do not throw unhandled exception when data is undefined in interceptor.reply
1 parent 008187b commit 2b694cc

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

lib/mock/mock-utils.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -124,8 +124,10 @@ function getResponseData (data) {
124124
return data
125125
} else if (typeof data === 'object') {
126126
return JSON.stringify(data)
127-
} else {
127+
} else if (data) {
128128
return data.toString()
129+
} else {
130+
return ''
129131
}
130132
}
131133

test/mock-interceptor.js

+40
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,46 @@ describe('MockInterceptor - reply options callback', () => {
107107
})
108108
})
109109

110+
test('should handle undefined data', t => {
111+
t = tspl(t, { plan: 2 })
112+
113+
const mockInterceptor = new MockInterceptor({
114+
path: '',
115+
method: ''
116+
}, [])
117+
const result = mockInterceptor.reply((options) => ({
118+
statusCode: 200,
119+
data: undefined
120+
}))
121+
t.ok(result instanceof MockScope)
122+
123+
// Test parameters
124+
125+
const baseUrl = 'http://localhost:9999'
126+
const mockAgent = new MockAgent()
127+
after(() => mockAgent.close())
128+
129+
const mockPool = mockAgent.get(baseUrl)
130+
131+
mockPool.intercept({
132+
path: '/test',
133+
method: 'GET'
134+
}).reply((options) => {
135+
t.deepStrictEqual(options, { path: '/test', method: 'GET', headers: { foo: 'bar' } })
136+
return { statusCode: 200, data: 'hello' }
137+
})
138+
139+
mockPool.dispatch({
140+
path: '/test',
141+
method: 'GET',
142+
headers: { foo: 'bar' }
143+
}, {
144+
onHeaders: () => { },
145+
onData: () => { },
146+
onComplete: () => { }
147+
})
148+
})
149+
110150
test('should error if passed options invalid', async (t) => {
111151
t = tspl(t, { plan: 4 })
112152

test/mock-utils.js

+6
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,12 @@ describe('getResponseData', () => {
174174
const responseData = getResponseData(new TextEncoder().encode('{"test":true}').buffer)
175175
t.ok(responseData instanceof ArrayBuffer)
176176
})
177+
178+
test('it should handle undefined', (t) => {
179+
t = tspl(t, { plan: 1 })
180+
const responseData = getResponseData(undefined)
181+
t.strictEqual(responseData, '')
182+
})
177183
})
178184

179185
test('getStatusText', (t) => {

0 commit comments

Comments
 (0)