Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(bypass): support modifying the bypassed request #2093

Merged
merged 2 commits into from
Mar 17, 2024
Merged
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 src/core/bypass.test.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Loading