nodejs / undici

An HTTP/1.1 client, written from scratch for Node.js
https://nodejs.github.io/undici
MIT License
6.25k stars 543 forks source link

Enable mocking of replies with Uint8Arrays #3660

Closed snovader closed 1 month ago

snovader commented 1 month ago

This would solve...

It's not currently possible to provide MockInterceptor with a Uint8Array and have those same bytes returned as the response of a fetch call. This example should illustrate the issue:

import assert from 'assert/strict';
import { MockAgent, setGlobalDispatcher } from 'undici';

const mockAgent = new MockAgent();
const mockPool = mockAgent.get('https://localhost');

mockAgent.disableNetConnect();
setGlobalDispatcher(mockAgent);

const testData = new TextEncoder().encode('test');

mockPool.intercept({ path: '/' }).reply(200, testData);

const response = await fetch('https://localhost');
const body = await response.bytes();

assert.deepEqual(body, testData);

This use case should ideally be possible but now results in the following error:

node:internal/modules/run_main:123
    triggerUncaughtException(
    ^

AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected

+ Uint8Array(33) [
+   123,
+   34,
+   48,
+   34,
+   58,
+   49,
+   49,
+   54,
+   44,
+   34,
+   49,
+   34,
+   58,
+   49,
+   48,
+   49,
+   44,
+   34,
+   50,
+   34,
+   58,
+   49,
+   49,
+   53,
+   44,
+   34,
+   51,
+   34,
+   58,
+   49,
+   49,
+   54,
+   125
- Uint8Array(4) [
-   116,
-   101,
-   115,
-   116
  ]
    at file:///mock-test.js:17:8
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5) {
  generatedMessage: true,
  code: 'ERR_ASSERTION',
  actual: Uint8Array(33) [
    123, 34, 48, 34, 58,  49, 49, 54, 44,
     34, 49, 34, 58, 49,  48, 49, 44, 34,
     50, 34, 58, 49, 49,  53, 44, 34, 51,
     34, 58, 49, 49, 54, 125
  ],
  expected: Uint8Array(4) [ 116, 101, 115, 116 ],
  operator: 'deepStrictEqual'
}

Node.js v22.9.0

The implementation should look like...

In addition to checking for Buffers here, Undici should also check for a valid Symbol.toStringTag of Uint8Array.

I have also considered...

Converting my Uint8Arrays to Buffers.

Additional context

I'd be happy to put up a PR with tests!

Uzlopak commented 1 month ago

Sorry, I did not see the last part where you wanted to provide a PR with tests.

snovader commented 1 month ago

No worries, I'm just happy to see this addressed so quickly!