Почему библиотека react-тестирования показывает ошибку ссылки

#reactjs #jestjs #react-testing-library

Вопрос:

Я пытаюсь запустить простой тест с использованием библиотеки react-testing, это в рамках проекта react без create-react-app (CRA) У меня есть базовая конфигурация веб-пакета, и я не знаю, нужно ли мне настраивать что-либо еще.

Вот тест

 import React from "react"; import "@testing-library/jest-dom/extend-expect"; import { render } from "@testing-library/react"; import { prettyDOM } from "@testing-library/dom"; import Button from "./Button";  test("renders content", () =gt; {  const props = {  text: "Test",  size: "lg",  color: "black",  type: "submit",  buttonClass: "button-oaauth-signup",  fullWidth: true,  };   const component = render(lt;Button {...props} /gt;);   component.getByText("Test"); });  

Вот мой пакет.json

 {  "name": "firmavirtual",  "version": "1.0.0",  "description": "",  "main": "index.js",  "scripts": {  "start": "webpack --mode=development",  "build": "webpack --mode=production",  "dev": "webpack-dev-server",  "test": "jest"  },  "keywords": [],  "author": "",  "license": "ISC",  "devDependencies": {  "@babel/core": "^7.15.8",  "@babel/preset-env": "^7.15.8",  "@babel/preset-react": "^7.14.5",  "@svgr/webpack": "^5.5.0",  "@testing-library/jest-dom": "^5.15.0",  "@testing-library/react": "^12.1.2",  "babel-jest": "^27.3.1",  "babel-loader": "^8.2.3",  "css-loader": "^6.5.0",  "file-loader": "^6.2.0",  "jest": "^27.3.1",  "node-sass": "^6.0.1",  "react-test-renderer": "^17.0.2",  "sass-loader": "^12.2.0",  "style-loader": "^3.3.1",  "svg-url-loader": "^7.1.1",  "webpack": "^5.60.0",  "webpack-cli": "^4.9.1",  "webpack-dev-server": "^4.3.1"  },  "dependencies": {  "@emotion/react": "^11.5.0",  "@emotion/styled": "^11.3.0",  "@mui/icons-material": "^5.0.5",  "@mui/material": "^5.0.6",  "react": "^17.0.2",  "react-dom": "^17.0.2",  "react-google-login": "^5.2.2",  "react-hook-form": "^7.18.0",  "react-icons": "^4.3.1",  "react-router-dom": "^5.3.0"  } }  

Вот мой webpack.config.js

 const webpack = require("webpack"); const path = require("path");  module.exports = {  mode: "development",  entry: "./src/index.js",  resolve: {  extensions: [".js", ".json", ".jsx", ".scss", ".svg", ".png", ".jpg"],  modules: [path.resolve(__dirname, "src"), "node_modules"],  },  output: {  filename: "bundle.js",  path: path.join(__dirname, "public"),  },  plugins: [new webpack.HotModuleReplacementPlugin({})],  module: {  rules: [  {  test: /.(js|jsx)$/,  exclude: /node_modules|bower_components/,  loader: "babel-loader",  options: {  presets: ["@babel/env", "@babel/preset-react"],  },  },  {  test: /.js$/,  exclude: /node_modules/,  loader: "babel-loader",  },  {  test: /.scss$/,  use: ["style-loader", "css-loader", "sass-loader"],  },  {  test: /.svg$/,  use: ["@svgr/webpack"],  },  {  test: /.(woff(2)?|ttf|eot)(?v=d .d .d )?$/,  use: [  {  loader: "file-loader",  options: {  name: "[name].[ext]",  outputPath: "assets/fonts/",  },  },  ],  },  ],  },  devtool: "eval-cheap-module-source-map",  devServer: {  static: path.join(__dirname, "public"),  port: 5000,  }, };  

Запуск теста запуска npm показывает эту ошибку

 gt; firmavirtual@1.0.0 test gt; jest   FAIL src/components/buttons/Button.test.js  ✕ renders content (2 ms)   ● renders content   The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.  Consider using the "jsdom" test environment.    ReferenceError: document is not defined   15 | };  16 |  gt; 17 | const component = render(lt;Button {...props} /gt;);  | ^  18 |  19 | component.getByText("Inicio con Google");  20 | });   at render (node_modules/@testing-library/react/dist/pure.js:83:5)  at Object.lt;anonymousgt; (src/components/buttons/Button.test.js:17:21)  Test Suites: 1 failed, 1 total Tests: 1 failed, 1 total Snapshots: 0 total Time: 5.179 s Ran all test suites.  

Есть идеи, как это исправить?

Комментарии:

1. Вы пробовали предлагаемое решение в ошибке? «Ошибка ниже может быть вызвана использованием неправильной тестовой среды…»

2. @JakeWorth ну, я думаю, мне нужно было поискать немного больше, в jest.config.js Я добавил testEnvironment: «jsdom», и это решило проблему. Глупая я

Ответ №1:

Ну, я думаю, мне нужно было поискать немного больше

В jest.config.js добавить

 module.exports = {  // Add the correct environment  testEnvironment: "jsdom",  moduleNameMapper: {  "\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":  "lt;rootDirgt;/__mocks__/fileMock.js",  "\.(css|less)$": "identity-obj-proxy",  }, };  

Это решило проблему. Глупая я