Skip to content

[Bug]: "expect" package now imports @types/node causing web projects to break #14418

@octogonz

Description

@octogonz

Version

>= 29.6.0

Steps to reproduce

Try to compile a TypeScript web project with Jest tests and code like this:

function asyncLoadStyles(): number {
  return setTimeout(() => {
    _themeState.runState.flushTimer = 0;
    flush();
  }, 0);
}

Expected behavior

It should compile because the compiler provides this definition:

lib.dom.d.ts

declare function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number;

Actual behavior

It fails to compile because expect now also brings in @types/node which has this conflicting definition:

globals.d.ts

declare function setTimeout(callback: (...args: any[]) => void, ms?: number, ...args: any[]): NodeJS.Timeout;

The error:

src/index.ts:224:3 - error TS2322: Type 'Timeout' is not assignable to type 'number'.

224   return setTimeout(() => {
      ~~~~~~~~~~~~~~~~~~~~~~~~~
225     _themeState.runState.flushTimer = 0;
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
226     flush();
    ~~~~~~~~~~~~
227   }, 0);
    ~~~~~~~~

Real world failing build:
microsoft/rushstack#3949
https://github.com/microsoft/rushstack/actions/runs/5873236375/job/15926196196?pr=3949

Additional context

This is a regression introduced by PR #14139

https://github.com/jestjs/jest/pull/14139/files#diff-1f480f1988b7f343469bb28b165fad08b4cadc37da379e655f2317d3c5f048b3

Why it's wrong: Jest itself is a Node.js application, but the TypeScript typings for Jest's test API should not assume that the unit tests are targeting Node.js runtime. For example if the unit tests are for a web application, then the setTimeout() declaration may be different from the Node.js environment.

Environment

System:
    OS: Windows 10 10.0.22621
    CPU: (14) x64 AMD Ryzen 7 3700X 8-Core Processor
  Binaries:
    Node: 16.15.1 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.19 - C:\Program Files\nodejs\yarn.CMD
    npm: 8.11.0 - C:\Program Files\nodejs\npm.CMD
    pnpm: 7.16.1 - C:\Program Files\nodejs\pnpm.CMD

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions