Skip to content

Commit

Permalink
fix(bypass): support modifying the bypassed request (#2093)
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito committed Mar 17, 2024
1 parent 9c9539f commit 2c8570b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
22 changes: 22 additions & 0 deletions src/core/bypass.test.ts
Expand Up @@ -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)
})
10 changes: 9 additions & 1 deletion src/core/bypass.ts
Expand Up @@ -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,
Expand Down

0 comments on commit 2c8570b

Please sign in to comment.