2

Having problems setting up ts-jest with jest-dom and react-testing library in a Next JS app, it seems I am unable to get access to any of the @testing-library/jest-dom matchers.

Anyone have any insights about this sort of setup with typescript and jest-dom? I've tried a few different solutions thus far including following the testing-library/jest-dom docs, and various other threads but to no success.

Below are the relevant dependencies and setup files...

// package.json

"dependencies": {
  "@types/testing-library__jest-dom": "^5.14.2",
  ..."
},
"devDependencies": {
  "@testing-library/jest-dom": "^5.16.0",
  "@testing-library/react": "^12.1.2",
  "@types/jest": "^27.0.3",
  "@types/react": "17.0.33",
  "ts-jest": "^27.0.7",
  "typescript": "^4.5.2",
   ..."
}
// jest.config.json
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  preset: 'ts-jest/presets/js-with-ts-esm', // or other ESM presets
  testEnvironment: 'jsdom',
  moduleDirectories: ["node_modules", "src"],
  verbose: true,
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
    globals: {
    // we must specify a custom tsconfig for tests because we need the typescript transform
    // to transform jsx into js rather than leaving it jsx such as the next build requires.  you
    // can see this setting in tsconfig.jest.json -> "jsx": "react"
    "ts-jest": {
      tsconfig: "tsconfig.jest.json"
    }
  },
  moduleNameMapper: {
    '\\.(css|scss|png|img)$': 'identity-obj-proxy',
    '\\.svg$': '<rootDir>/__mocks__/svg.js',
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': "<rootDir>/svgTransform.js"
  },
  "transform": {
    "^.+\\.tsx?$": "ts-jest",
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': "<rootDir>/svgTransform.js"
 },
 setupFilesAfterEnv: ['<rootDir>/setupTests.ts'],
};
// tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "DOM",
      "DOM.Iterable",
      "ES2015",
      "ES2016.Array.Include",
      "ES2017.Object",
      "ES2017.String",
      "ES2018.AsyncIterable",
      "ES2018.Promise",
      "ES2019.Array",
      "ES2019.Object",
      "ES2019.String",
      "ES2019.Symbol",
      "ES2020.Promise",
      "ES2020.String",
      "ES2020.Symbol.WellKnown",
      "ESNEXT"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": false,
    "jsx": "preserve",
    "baseUrl": ".",
    "paths": {
      "*": [
        "src/*"
      ]
    },
    "incremental": true
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "setupTests.ts",
    "src",
    "src/@deprecated/pages/Property/components/PropertyInfo/components/Invest/components/Calculator/Calculator.spec.jsx", "src/@deprecated/pages/Property/components/PropertyInfo/components/Invest/components/Calculator/Calculator.spec.jsx", "jest.config.js"  ],
  "exclude": [
    "node_modules"
  ],
  "types": ["node", "jest", "@types/testing-library__jest-dom"]
}

// setupTests.ts
import '@testing-library/jest-dom/extend-expect'

// tsconfig.jest.json
{
    "extends": "./tsconfig.json",
    "compilerOptions": {
      "jsx": "react-jsx"
    }
  }

And lastly the spec file where the .toBeInTheDocument() matcher method isn't recognized.

// Calculator.spec.tsx
import React from 'react'
import { expect, test } from '@jest/globals'
import { render, screen, cleanup } from '@testing-library/react'
import { Calculator } from './Calculator'


afterEach(cleanup);

describe('<Calculator />', () => {
    test('Slider is rendered', () => {
      render(<Calculator rentalDividends={12} returnOnInvestment={5} fundingTarget={363500} brickPrice={1000}/>)
      const slider = screen.getByTestId("slider")
      expect(slider).toBeInTheDocument()
})
Aaron Z
  • 73
  • 1
  • 5
  • Try putting console output in your jest-setup file to ensure it is getting called correctly. Try only importing `'@testing-library/jest-dom'`. Try putting that import statement at the header of your test file. – HaveSpacesuit Dec 07 '21 at 15:24
  • 2
    Are you sure you need to manually import `expect` and `test` ? You might want to try to remove this line, and see if it fixes the issue – aquinq Dec 08 '21 at 10:14
  • @acuinq ... yep that solved it. Merci beaucoup – Aaron Z Dec 13 '21 at 09:52

1 Answers1

1

Seems like there are some dependency issues with jest and so one workaround is:

Try installing jest-without-globals

npm i -D jest-without-globals

Then import except and test from it.

import { expect, test } from 'jest-without-globals'
whitetiger1399
  • 423
  • 3
  • 6