nodejs / undici

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

with custom agent mockPool.intercepts body is asyncGenerator #3887

Closed smoebody closed 2 days ago

smoebody commented 3 days ago

Bug Description

When setting a custom agent as option for MockAgent the body property is of type asyncGenerator and therefore never matches my source body

Reproducible By

A minimal example follows

import { Agent, fetch, setGlobalDispatcher } from "undici";
import { MockAgent } from "undici";

const agent = new Agent();
const mockAgent = new MockAgent({ agent });
const mockPool = mockAgent.get("http://localhost");
setGlobalDispatcher(mockAgent)

mockPool
  .intercept({
    path: "/test",
    method: "POST",
    body: (body) => {
      console.log(body);
      return true;
    },
  })
  .reply(204);

(async () => {
  await fetch("http://localhost/test", {
    dispatcher: agent,
    method: "POST",
    body: "test",
  });
})().then(() => {
  process.exit()
})

The output is

Object [AsyncGenerator] {}
Object [AsyncGenerator] {}

Expected Behavior

The output should be

test

when removing the dispatcher property from the fetch call it works as intended (i guess, although test is printed twice)

Environment

Docker-Image: node:22-alpine Kernel: 6.11.8-300.fc41.x86_64 x86_64 Linux Node: v22.11.0 undici: 6.21.0

KhafraDev commented 3 days ago

An easy workaround is to do

const agent = new Agent();
agent.isMockActive = true
metcoder95 commented 3 days ago

Is this a bug or is expected @KhafraDev?

KhafraDev commented 2 days ago

Ignore my previous answer, fetch's dispatcher option takes precedence over the global dispatcher.

await fetch("http://localhost/test", {
    dispatcher: agent,
    method: "POST",
    body: "test",
  });

The dispatcher has to be mockAgent in this case, or the option has to be unset, in which case it'll fallback to the global dispatcher (being mockAgent).