Skip to content

Commit

Permalink
test: add unit test for verifying XHR body consumption (#632)
Browse files Browse the repository at this point in the history
  • Loading branch information
robbtraister committed Sep 13, 2024
1 parent 532eac8 commit 0fd1ac6
Showing 1 changed file with 33 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
* @note This issue is only reproducible in "happy-dom".
* @see https://github.com/mswjs/msw/issues/1816
*/
import { beforeAll, afterAll, it, expect } from 'vitest'
import { beforeAll, afterAll, describe, it, expect } from 'vitest'
import axios from 'axios'
/**
* @note Use `Response` from Undici because "happy-dom"
* does not implement ReadableStream at all. They use
* Node's Readable instead, which is completely incompatible.
*/
import { Response as UndiciResponse } from 'undici'
import { Response as UndiciResponse, Request as UndiciRequest } from 'undici'
import { XMLHttpRequestInterceptor } from '../../../../src/interceptors/XMLHttpRequest'

const request = axios.create({
Expand Down Expand Up @@ -39,3 +39,34 @@ it('performs a request with the "xhr" axios adapter', async () => {
expect(res.status).toBe(200)
expect(res.data).toBe('Hello world')
})

describe("wth the undici Request", () => {
/**
* @note Use `Request` from Undici because "happy-dom"
* does not prevent cloning after consuming the body buffer
* This will verify standard behavior
*/
const NativeRequest = global.Request
beforeAll(() => {
global.Request = UndiciRequest as unknown as typeof Request
})

afterAll(() => {
global.Request = NativeRequest
})

it('performs a POST request with the "xhr" axios adapter', async () => {
interceptor.once('request', async ({ controller, request }) => {
// consume the body to ensure respondWith doesn't try to read something it can't
await request.arrayBuffer()

controller.respondWith(
new UndiciResponse('Hello world') as unknown as Response
)
})

const res = await request.post('/resource', { field: 'value' })
expect(res.status).toBe(200)
expect(res.data).toBe('Hello world')
})
});

0 comments on commit 0fd1ac6

Please sign in to comment.