Skip to content

Commit

Permalink
fix: do not throw unhandled exception when data is undefined in inter…
Browse files Browse the repository at this point in the history
…ceptor.reply
  • Loading branch information
frederikprijck committed Jan 31, 2025
1 parent 008187b commit 2b694cc
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/mock/mock-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 ''
}
}

Expand Down
40 changes: 40 additions & 0 deletions test/mock-interceptor.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 })

Expand Down
6 changes: 6 additions & 0 deletions test/mock-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down

0 comments on commit 2b694cc

Please sign in to comment.