Skip to content

MockAgent as global dispatcher broken since version 8.0.3 #5036

@targos

Description

@targos

Bug Description

In versions 8.0.3 and 8.1.0, if I set a MockAgent as global dispatcher, it no longer intercepts native Node.js fetch queries.

Reproducible By

test.js:

import { MockAgent, setGlobalDispatcher } from 'undici';

const agent = new MockAgent();
agent.disableNetConnect();

setGlobalDispatcher(agent);

agent.get('https://example.com')
  .intercept({
    method: 'GET',
    path: '/v1/test',
  })
  .reply(() => {
    return {
      statusCode: 200,
      data: { test: 123 },
    }
  });

const req = await fetch('https://example.com/v1/test')
console.log(req.status);

const data = await req.json();
console.log(data);
node test.js

Expected Behavior

It should intercept the query and return the mocked response.

Logs & Screenshots

➤ node test.js
404
<anonymous_script>:1
<!doctype html><html lang="en"><head><title>Example Domain</title><meta name="viewport" content="width=device-width, initial-scale=1"><style>body{background:#eee;width:60vw;margin:15vh auto;font-family:system-ui,sans-serif}h1{font-size:1.5em}div{opacity:0.8}a:link,a:visited{color:#348}</style></head><body><div><h1>Example Domain</h1><p>This domain is for use in documentation examples without needing permission. Avoid use in operations.</p><p><a href="https://iana.org/domains/example">Learn more</a></p></div></body></html>
^

SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON
    at JSON.parse (<anonymous>)

Environment

Tested with Node.js 25.9.0 and 24.15.0.

Additional context

8.0.1 and 8.0.2 worked as expected. 8.0.0 also had this issue.

/cc @mcollina

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions