diff --git a/src/core/bypass.test.ts b/src/core/bypass.test.ts index 385234d10..bef858bcb 100644 --- a/src/core/bypass.test.ts +++ b/src/core/bypass.test.ts @@ -45,3 +45,25 @@ it('returns bypassed request given request instance', async () => { 'x-msw-intention': 'bypass', }) }) + +it('allows modifying the bypassed request instance', async () => { + const original = new Request('http://localhost/resource', { + method: 'POST', + body: 'hello world', + }) + const request = bypass(original, { + method: 'PUT', + headers: { 'x-modified-header': 'yes' }, + }) + + expect(request.method).toBe('PUT') + expect(Object.fromEntries(request.headers.entries())).toEqual({ + 'x-msw-intention': 'bypass', + 'x-modified-header': 'yes', + }) + expect(original.bodyUsed).toBe(false) + expect(request.bodyUsed).toBe(false) + + expect(await request.text()).toBe('hello world') + expect(original.bodyUsed).toBe(false) +}) diff --git a/src/core/bypass.ts b/src/core/bypass.ts index e467cf30c..26d3afb2f 100644 --- a/src/core/bypass.ts +++ b/src/core/bypass.ts @@ -15,7 +15,15 @@ export type BypassRequestInput = string | URL | Request * @see {@link https://mswjs.io/docs/api/bypass `bypass()` API reference} */ export function bypass(input: BypassRequestInput, init?: RequestInit): Request { - const request = input instanceof Request ? input : new Request(input, init) + // Always create a new Request instance. + // This way, the "init" modifications will propagate + // to the bypass request instance automatically. + const request = new Request( + // If given a Request instance, clone it not to exhaust + // the original request's body. + input instanceof Request ? input.clone() : input, + init, + ) invariant( !request.bodyUsed,