首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Webpack 5& Jest -属性“toBeInTheDocument”在“JestMatchers<HTMLElement>”类型上不存在

Webpack 5& Jest -属性“toBeInTheDocument”在“JestMatchers<HTMLElement>”类型上不存在
EN

Stack Overflow用户
提问于 2021-10-27 11:23:56
回答 2查看 2.7K关注 0票数 3

我无法让Jest的打字和Webpack 5和TypeScript一起工作,我已经尝试过针对同样的问题的其他解决方案。在下面的示例测试中,问题只与“屏幕”和"toBeInTheDocument“有关。我倾向于将其作为一个ESLint配置问题。

我不能运行这些测试,它们在Property 'toBeInTheDocument' does not exist on type 'JestMatchers<HTMLElement>'.中失败了。我用的是Yarn 3.1.0。我尝试过this答案和其他许多方法,包括通过tsconfig.json导入类型。我做错了什么?

示例测试(src/components/Example/spec/test.spec.tsx):

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
/* 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

代码语言:javascript
运行
复制
{
  "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"
  }
}

tsconfig.json

代码语言:javascript
运行
复制
{
  "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"
  ]
}

setupTests.ts是正义的:import '@testing-library/jest-dom/extend-expect';

谢谢你的指点。

EN

回答 2

Stack Overflow用户

发布于 2022-05-15 01:04:54

使用以下方法安装类型:

代码语言:javascript
运行
复制
npm i @types/testing-library__jest-dom -D
票数 3
EN

Stack Overflow用户

发布于 2022-05-12 12:16:58

请确保项目中安装了正确的类型。即

代码语言:javascript
运行
复制
npm i -D @testing-library/jest-dom@^4.2.4

根据我的经验,version 5.x中似乎缺少类型文本类型

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69737766

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档