Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VSCode does not recognize jest custom matcher

Tags:

jestjs

ts-jest

I'm currently struggling with making a Jest custom matcher work in VSCode with typescript.

I wrote a custom matchers file like the following (I've simplified the test for brevity reasons):

export {}

declare global {
  namespace jest {
    interface Matchers<R, T = {}> {
      toSucceed(): R
    }
  }
}

function toSucceed(this: jest.MatcherContext, received: Result<any>): any {
  return {
    pass: true,
    message: () => 'Custom matcher message',
  }
}

expect.extend({
  toSucceed,
})

I included this file path in my jest.config.ts under the tag setupFilesAfterEnv.

Then I wrote tests like:

it('should pass', () => {
  expect(foo()).toSucced()
})

All this configuration works fine, but I still get a VSCode inline error: Property 'toSucceed' does not exist on type 'JestMatchers<any>'

JestMatchers is a type definition inside the @types/jest root, since it is a type I cannot augment it directly.

Have anyone experienced any similar problem?

like image 264
Pedro Calderon Avatar asked Dec 06 '25 06:12

Pedro Calderon


2 Answers

Did you remember to add the type definitions to your tsconfig?

For me it works fine when I put the type definition in a d.ts file at the root level, and add that path to the "include" option in my tsconfig:

{
  // Some other config
  "include": [
    "custom-matchers.d.ts"
  ]
}

Haven't tested with your custom matcher specifically, but I had a similar issue that I resolved like this.

So your custom-matchers.d.ts would be:

export {}

declare global {
  namespace jest {
    interface Matchers<R, T = {}> {
      toSucceed(): R
    }
  }
}
like image 72
Oscar Carlström Avatar answered Dec 11 '25 09:12

Oscar Carlström


I encountered a similar error message when the namespace declaration of "interface Matchers" was incorrect. After fixing that, a custom matcher appeared in jestMatchers, too. Matchers and jestMatchers are connected.

Your code works fine for me—except for the undefined Result<any>—so you can try to directly import in test and see if Visual Studio Code can understand the declaration:

import "./toSucceed";

If direct import works for you, I would guess that there's a problem with the jest extension which helps Visual Studio Code understand jest.config.

like image 45
Mike Avatar answered Dec 11 '25 07:12

Mike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!