nodejs / nodejs/undici

Reading request body never consumes anything when using Jest mock timers

Open
#1,251 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug fetch Status: help-wanted
Dominant language
JavaScript
Stars
7.7k
Forks
880
Avg merge
2d 16h
Merged PRs (30d)
68

Description

Bug Description

Modern Jest fake timers seem to cause problems for reading the body of Undici Requests.

Reproducible By

The following code deadlocks:

import { Request } from 'undici'

beforeEach(() => {
  const mockTimeBase = 1643948235000

  jest.useFakeTimers('modern')
  jest.setSystemTime(mockTimeBase)
})

afterEach(() => {
  jest.useRealTimers()
})

test('request and jest fake timers problem', async () => {
    const req = new Request('http://example.com', { method: 'POST', body: 'some message' })
    console.log('Awaiting undici request')
    console.log(await req.text())
    console.log('Done')
})

Expected Behavior

The request body should be consumed during reading even when using fake timers.

Logs & Screenshots

Environment

Node 17.6
Jest 27.2.5
Undici 4.14.1 (also reproduced on 4.13.0)

Additional context

Removing the use of fake timers or using the Node Request builtin (i.e. comment out the first line) causes the test to complete as expected. If you convert the .text() invocation to instead call read() on the reader for the body, read() always returns 'some message' as the value and done is always false. Jest fake timers say they impact queueMicrotask & I noticed the streams in undici use queueMicrotask which may be related to the problem. Even if there's no way to strictly fix this within undici, it would be nice for there to be an escape hatch of some kind (e.g. some callback I can register to call jest.runAllTimers probably fixes the issue)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the provided Jest reproduction with modern fake timers and compare req.text() with direct body-reader read() behavior. Investigate the interaction between Undici request-body streams and queueMicrotask under fake timers; done means the request body is consumed and the test completes without requiring real timers.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, nodejs
Domain
api, backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.