Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions packages/core/src/__tests__/create-request-client.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import btoa from 'btoa-lite'
import createTestServer from 'create-test-server'
import createRequestClient from '../create-request-client'
import { Response } from '../fetch'

describe('createRequestClient', () => {
it('should create a request client instance that has Segment defaults', async () => {
Expand Down Expand Up @@ -111,4 +112,25 @@ describe('createRequestClient', () => {
})
await server.close()
})

it('should emulate an HTTP response if emulateHttpResponse property is set', async () => {
const server = await createTestServer()
server.get('/', (_request, response) => {
response.json({ greeting: 'This is the server response' })
})

const request = createRequestClient()

const emulateHttpResponse = new Response(JSON.stringify({ hello: 'This is the emulated response' }), {
headers: { 'Content-Type': 'application/json' },
status: 200,
statusText: 'OK'
})

await expect(request(server.url, { method: 'get', emulateHttpResponse })).resolves.toMatchObject({
data: expect.objectContaining({ hello: 'This is the emulated response' })
})

await server.close()
})
})
10 changes: 10 additions & 0 deletions packages/core/src/request-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ export interface RequestOptions extends Omit<RequestInit, 'headers'> {
* Uses the provided https.Agent
*/
agent?: https.Agent
/**
* Used to emulate an http request.
* If set, instead of making a real HTTP request, the provided response will be returned.
*/
emulateHttpResponse?: Response
}

/**
Expand Down Expand Up @@ -357,6 +362,11 @@ class RequestClient {
}
}

// If we have an emulateHttpResponse, return it instead of making a real request
if (this.options.emulateHttpResponse) {
return Promise.resolve(this.options.emulateHttpResponse)
}

if (this.options.timeout === false) {
return fetch(this.request.clone())
}
Expand Down
Loading
Loading