vitest-dev / vitest

Next generation testing framework powered by Vite.
https://vitest.dev
MIT License
13.15k stars 1.19k forks source link

`expect.extend`: `MatchersObject` functions do not receive the correct `this` type when generic #6967

Open 6XGate opened 3 days ago

6XGate commented 3 days ago

Describe the bug

When using using expect.extend, generic functions on the passed object has the wrong this type. Likely due missing & ThisType<T> on the end of the type definition type MatchersObject<T extends MatcherState = MatcherState> = Record<string, RawMatcherFn<T>>

Reproduction

  expect.extend({
    toBeLike<T>(received: unknown, expected: T) {
      const { isNot, utils } = this
      return {
        pass: received == expected,
        message: () => isNot
          ? `Expected ${utils.stringify(received)} to not be like ${utils.stringify(expected)}`
          : `Expected ${utils.stringify(received)} to be like ${utils.stringify(expected)}`,
        actual: received,
        expected
      }
    },
  })

This results in a TS2339 error on the two message template string warning Property 'stringify' does not exist on type 'RawMatcherFn<MatcherState>'

System Info

System:
    OS: macOS 15.1.1
    CPU: (14) arm64 Apple M3 Max
    Memory: 350.03 MB / 36.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.15.0 - ~/.nvm/versions/node/v20.15.0/bin/node
    Yarn: 1.22.22 - ~/.nvm/versions/node/v20.15.0/bin/yarn
  Browsers:
    Chrome: 131.0.6778.86
    Safari: 18.1.1
    Firefox: 132.0.2
    Firefox Developer Edition 133.0b9
  npmPackages:
    @vitejs/plugin-vue: ^5.2.0 => 5.2.0
    @vitejs/plugin-vue-jsx: ^4.1.0 => 4.1.0
    @vitest/coverage-v8: ^2.1.5 => 2.1.5
    vite: ^5.4.11 => 5.4.11
    vitest: ^2.1.5 => 2.1.5

Used Package Manager

yarn

Validations

hi-ogawa commented 1 day ago

Likely due missing & ThisType<T> on the end of the type definition type MatchersObject<T extends MatcherState = MatcherState> = Record<string, RawMatcherFn<T>>

Not sure where this would be. Feel free to send a PR if you have a fix :+1: