Skip to content

Commit

Permalink
fix(xhr): clone the request before calculating its body size (#632)
Browse files Browse the repository at this point in the history
Co-authored-by: Artem Zakharchenko <[email protected]>
  • Loading branch information
robbtraister and kettanaito committed Sep 13, 2024
1 parent 4227c6e commit 44276ef
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
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')
})

0 comments on commit 44276ef

Please sign in to comment.