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(xhr): clone the request before calculating its body size #632

Merged
merged 3 commits into from
Sep 13, 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
4 changes: 2 additions & 2 deletions src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ export class XMLHttpRequestController {

// Delegate request handling to the consumer.
const fetchRequest = this.toFetchApiRequest(requestBody)
this[kFetchRequest] = fetchRequest
this[kFetchRequest] = fetchRequest.clone()

const onceRequestSettled =
this.onRequest?.call(this, {
Expand Down Expand Up @@ -296,7 +296,7 @@ export class XMLHttpRequestController {
*/
if (this[kFetchRequest]) {
const totalRequestBodyLength = await getBodyByteLength(
this[kFetchRequest].clone()
this[kFetchRequest]
)

this.trigger('loadstart', this.request.upload, {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// @vitest-environment jsdom
import { vi, beforeAll, afterEach, afterAll, it, expect } from 'vitest'
import { XMLHttpRequestInterceptor } from '../../../../src/interceptors/XMLHttpRequest'
import { createXMLHttpRequest } from '../../../helpers'

const interceptor = new XMLHttpRequestInterceptor()

beforeAll(() => {
interceptor.apply()
})

afterEach(() => {
interceptor.removeAllListeners()
})

afterAll(() => {
interceptor.dispose()
})

it('does not lock the request body stream when calculating the body size', async () => {
interceptor.on('request', async ({ request, controller }) => {
// Read the request body in the interceptor.
const buffer = await request.arrayBuffer()
controller.respondWith(new Response(buffer))
})

const uploadLoadStartListener = vi.fn()
const request = await createXMLHttpRequest((request) => {
request.upload.addEventListener('loadstart', uploadLoadStartListener)
request.open('POST', '/resource')
request.send('request-body')
})

// Must calculate the total request body size for the upload event.
const progressEvent = uploadLoadStartListener.mock.calls[0][0]
expect(progressEvent.total).toBe(12)

// Must be able to read the request in the interceptor
// and use its body as the mocked response body.
expect(request.responseText).toBe('request-body')
})
Loading