TypeScript errors with vitest
unikitty37 opened this issue · 2 comments
In a TypeScript test file, I have this line of code:
expect(screen.getByTestId('card-info')).toHaveTextContent(/^No information available\.$/)However, it produces the TypeScript error "Property 'toHaveTextContent' does not exist on type 'Assertion'."
The code still executes properly, but I would like to have TypeScript errors cause a CI pipeline failure, and I can't do this while it's throwing this error (it also makes the VSCode window very ugly with all the red blocks :)
testing-library/react-testing-library#37 merges documentation on fixing this, but a later PR moves it to dom-testing-library — and it's since vanished from there. I'm at a loss to find out how to fix this.
I've already run pnpm i -D @types/testing-library__jest-dom. I'm running import '@testing-library/jest-dom' in a vitest.globals.ts file, and putting a console.log in there confirms it's running for each test file — but TypeScript doesn't appear to be taking any notice of it. I have compilerOptions.types: ['vitest/globals'] in my tsconfig.json.
Short of changing the extension to .js and doing away with type checking in my tests, how can I get rid of this error?
Hi @unikitty37! I'm not affiliated with this project, but I do use it successfully with Vitest and TypeScript. Since this is a @testing-library/jest-dom issue and not @testing-library/svelte issue, you should check out the @testing-library/jest-dom docs, which spell out exactly how to use it with Vitest + TypeScript.
The usage instructions are very simple as of the recent v6 release. You also no longer need to install @types/testing-library__jest-dom.
With Vitest
If you are using vitest, this module will work as-is, but you will need to use a different import in your tests setup file. This file should be added to the setupFiles property in your vitest config:
// In your own vitest-setup.js (or any other name) import '@testing-library/jest-dom/vitest' // In vitest.config.js add (if you haven't already) setupFiles: ['./vitest-setup.js']
Following the above instructions (swapping .js for .ts) gets TypeScript working automatically, provided your vitest-setup.ts file is included in your tsconfig.json. If your setup file is not included in your tsconfig.json file, you can also add "@testing-library/jest-dom/vitest" to compilerOptions.types
Thanks! I'll give that a try…