Rei
Rei

Reputation: 47

Webpack 5 & Jest - Property 'toBeInTheDocument' does not exist on type 'JestMatchers<HTMLElement>'

I can't get the typings for Jest to work with Webpack 5 and TypeScript, I've tried other solutions for the same problem. The problem is only with "screen" and "toBeInTheDocument" in my example test below. I'm leaning toward it being an ESLint configuration issue.

I can't run the tests, they fail with Property 'toBeInTheDocument' does not exist on type 'JestMatchers<HTMLElement>'.. I'm using Yarn 3.1.0. I've tried this answer and many others, including importing the types through tsconfig.json. What am I doing wrong?

Example test (src/components/Example/spec/test.spec.tsx):

import * as React from 'react';
import { render, screen } from '@testing-library/react';
import { Example } from './Example';
import "@testing-library/jest-dom/extend-expect";
import "@testing-library/jest-dom";

test("Renders correctly", () => {
  render(<Example />);
  const example = screen.getByAltText("Example");
  expect(example).toBeInTheDocument();
});

jest.config.js:

module.exports = {
  // An array of directory names to be searched recursively up from the requiring module's location
  moduleDirectories: ['node_modules', '<rootDir>/src'],

  // A map to module names that allow stubbing out resources with a single module
  moduleNameMapper: {
    '\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js',
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/__mocks__/fileMock.js',
  },

  // Preset for our Jest configuration base
  preset: 'ts-jest/presets/js-with-ts',

  setupFilesAfterEnv: ['<rootDir>/setupTests.ts'],

  // Environment used for testing
  testEnvironment: 'jsdom',
};

webpack.config.js:

/* eslint-disable */
const { ModuleFederationPlugin } = require('webpack').container;
const path = require('path');
const packageJsonName = require('./package.json').name;
const packageJsonDeps = require('./package.json').dependencies;
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: path.resolve(__dirname, 'src', 'index.ts'),
  devServer: {
    client: {
      overlay: true,
    },
    static: {
      directory: './dist',
    },
    port: 3001,
    historyApiFallback: true
  },
  module: {
    rules: [
      {
        test: /\.(tsx|ts|jsx)?$/,
        //exclude: /node_modules/,
        use: [
          {
            loader: 'ts-loader',
            options: {
              experimentalWatchApi: true,
              transpileOnly: true,
            },
          },
        ],
      },
      {
        test: /\.js$/,
        enforce: 'pre',
        use: ['source-map-loader'],
      },
    ],
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: 'auto',
  },
  resolve: {
    cacheWithContext: false,
    extensions: ['.js', '.ts', '.tsx', '.jsx'],
    plugins: [
      new TsconfigPathsPlugin({
        configFile: path.resolve(__dirname, './tsconfig.json'),
      }),
    ],
    symlinks: false,
  },
};

package.json:

{
  "scripts": {
    "start": "webpack-cli serve",
    "build": "webpack --mode production",
    "dev": "webpack serve --progress",
    "test": "jest",
    "test:coverage": "jest --coverage --watchAll=false",
    "test:watch": "jest --watch"
  },
  "dependencies": {
    "react": "17.0.2",
    "react-router-dom": "^5.2.0",
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "12.1.2",
    "@testing-library/user-event": "13.5.0",
    "@types/jest": "27.0.2",
    "@types/react": "^17.0.33",
    "@types/react-router-dom": "5.3.2",
    "@typescript-eslint/eslint-plugin": "5.2.0",
    "@typescript-eslint/parser": "4.33.0",
    "eslint": "7.32.0",
    "eslint-config-prettier": "8.3.0",
    "eslint-plugin-import": "2.25.2",
    "eslint-plugin-jest": "25.2.2",
    "eslint-plugin-react": "7.26.1",
    "eslint-plugin-react-hooks": "4.2.0",
    "jest": "^27.3.1",
    "prettier": "2.4.1",
    "ts-jest": "^27.0.7",
    "ts-loader": "^9.2.6",
    "tslib": "^2.3.1",
    "typescript": "~4.3.5",
    "webpack": "5",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.3.1"
  }
}

And tsconfig.json:

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "baseUrl": ".",
    "declaration": true,
    "esModuleInterop": true,
    "importHelpers": true,
    "jsx": "react",
    "lib": ["es6", "dom"],
    "module": "esnext",
    "moduleResolution": "node",
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedParameters": true,
    "outDir": "dist",
    "resolveJsonModule": true,
    "rootDir": ".",
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "target": "es6"
  },
  "include": ["**/*.ts", "**/*.tsx", "**/*.jsx", "**/*.js"],
  "exclude": [
    "dist",
    "node_modules"
  ]
}

And setupTests.ts is just: import '@testing-library/jest-dom/extend-expect';

Thanks for any pointers.

Upvotes: 4

Views: 8536

Answers (2)

Neto
Neto

Reputation: 431

Install the types using:

npm i @types/testing-library__jest-dom -D

Upvotes: 5

Alexey Chekmarev
Alexey Chekmarev

Reputation: 31

Please make sure that the correct types are installed in your project. i.e.

npm i -D @testing-library/jest-dom@^4.2.4

From my experience the Typescript types seem to be missing from version 5.x

Upvotes: 1

Related Questions