Skip to content

[Bug]: Using @jest/globals expect breaks extensions #12267

@johncrim

Description

@johncrim

Version

27.4.7

Steps to reproduce

git clone [email protected]:johncrim/jest-bugs.git
yarn
yarn test-esm

There are two versions of the same test, one using

import { expect } from '@jest/globals';

the other using the ambient/global expect.

The test using import { expect } from '@jest/globals'; fails with:

 PASS  src/expect-extension-no-jest-globals.spec.ts
 FAIL  src/expect-extension-jest-globals.spec.ts
  ● Test suite failed to run

    src/expect-extension-jest-globals.spec.ts:6:18 - error TS2339: Property 'toIncludeSameMembers' does not exist on type 'Matchers<void, number[]>'.

    6   expect([1, 2]).toIncludeSameMembers([2, 1]);

because the type returned from expect() in '@jest/globals' (Matchers<void, T> in expect module) does not match the type returned from expect() in @types/jest (jest.JestMatchers<T>).

Expected behavior

expect extension typing continues to work whether you're importing from @jest/globals or not.

Actual behavior

expect extensions fail to compile when importing expect from @jest/globals. If you can get around the typing issue (via casting or any or creating a global type def file to fix the issue) the runtime behavior works as expected.

Additional context

This breaks all expect extensions in libraries I'm aware of, including:

  • jest-extended
  • ngneat/spectator
  • expect-more-jest

It also breaks anyone using private expect extensions using the approach that is widely documented and used - a file like:

// my-jest-matchers.d.ts
declare namespace jest {
  interface Matchers<R> {
    equalsFoo(message: string): R;
  }
}

will no longer enable compilation given expect(x).equalsFoo('message');.

The obvious workaround is "don't use @jest/globals", but that is not viable in many codebases - particularly if using ES Modules. In our codebase, we have jasmine types and jest types, and using @jest/globals is necessary now that we've changed to ES Modules.

I believe this is the same issue as #10642. #10642 was correctly reported, but it was incorrectly closed. This comment about creating a type def file for expect extensions is helpful, but is not a fix for #10642. Hopefully this issue provides more clarity.

Environment

System:
    OS: Windows 10 10.0.19044
    CPU: (12) x64 Intel(R) Core(TM) i9-8950HK CPU @ 2.90GHz
  Binaries:
    Node: 16.12.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.15 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 8.1.0 - C:\Program Files\nodejs\npm.CMD
  npmPackages:
    jest: ^27.3.1 => 27.4.7

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