jest-dom icon indicating copy to clipboard operation
jest-dom copied to clipboard

Property 'toHaveTextContent' does not exist on type 'Assertion<HTMLElement>'.

Open drichar opened this issue 1 year ago • 3 comments

  • @testing-library/jest-dom version: 6.4.8
  • node version: 20.14.0
  • vitest version: 2.0.4
  • pnpm version: 9.4.0
  • @testing-library/react version: 16.0.0

Relevant code or config:

describe('ellipseAddressJsx', () => {
  it('should return ellipsed address with specified width', () => {
    const address = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
    const width = 4

    const { container } = render(ellipseAddressJsx(address, width))

    expect(container).toHaveTextContent('aaaa…aaaa')
  })
})

What you did:

Upgraded from vitest 2.0.3 from 2.0.4

What happened:

After upgrading to [email protected] this TypeScript error appeared in every @testing-library/jest-dom assertion: image

Reproduction:

https://codesandbox.io/p/devbox/silly-panna-vx86jv

See src/utils.test.tsx

Problem description:

Following the instructions for using @testing-library/jest-dom with Vitest provided here no longer seems to work in the latest version of Vitest. (Confirmed this is also the case for [email protected])

Suggested solution:

As suggested here: https://github.com/testing-library/jest-dom/issues/546#issuecomment-1800436478

In tsconfig.json:

{
  "compilerOptions": {
    "types": ["@testing-library/jest-dom"]
  },
}

This resolves the issue.

drichar avatar Aug 02 '24 03:08 drichar

Does https://github.com/testing-library/jest-dom/pull/621 fix the problem? If I understand correctly, this is something that consumers of the library would need to do in their own repos, so all we can do is document this in the README, right?

gnapse avatar Aug 02 '24 20:08 gnapse

Instead of changing your "types", add your vitest.setup.ts file to the "include" array in your tsconfig.json.

tsconfig.json

{
  ...
  "include": ["src", "vitest.setup.ts"],
}

See With TypeScript in the jest-dom README.md, which uses "./jest-setup.ts" in the example.

With TypeScript

If you're using TypeScript, make sure your setup file is a .ts and not a .js to include the necessary types.

You will also need to include your setup file in your tsconfig.json if you haven't already:

  // In tsconfig.json
  "include": [
    ...
    "./jest-setup.ts"
  ],

andykenward avatar Aug 04 '24 11:08 andykenward

Can you make a review of that PR and request/suggest changes?

gnapse avatar Aug 05 '24 15:08 gnapse