【问题标题】:Jest can't resolve project paths in react appJest 无法解析 React 应用程序中的项目路径
【发布时间】:2020-04-30 02:01:39
【问题描述】:

所以,我正在学习在我正在从事的项目中使用 jest 和 react-testing-library。这是我正在测试的组件的代码:

//DefaultLayout.js

import React, { Component, Suspense } from 'react';
import Header from 'components/Header/Header.js'

...

然后是测试文件:

//DefaultLayout.test.js

import React from 'react'
import { render, cleanup } from "@testing-library/react"
import '@testing-library/jest-dom'
import DefaultLayout from "./DefaultLayout.js"

...

现在,当我运行 npm test 时,我得到了:

Test suite failed to run

    Cannot find module 'components/Header/Header.js' from 'DefaultLayout.js'

      2 | import { Redirect, Route, Switch } from 'react-router-dom';
      3 | import * as router from 'react-router-dom';
    > 4 | import Header from 'components/Header/Header.js'
        | ^

现在,为了使导入工作,我有一个像这样的jsconfig.json 文件:

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "*": ["src/*"]
    }
  }
}

包括components 在内的所有文件夹都在src 目录中。我知道 jest 没有导入此配置,并且我需要为 jest 再次设置它。我只是不明白该怎么做。

我创建了一个jest.conf 文件,但它不起作用:

{
  "transform": {
    "^.+\\.(js|jsx)$": "<rootDir>/src"
  },
}

这是我最近的尝试。 jest.conf 文件位于项目的根目录中。

任何帮助都会很棒。

【问题讨论】:

    标签: reactjs jestjs react-testing-library


    【解决方案1】:

    好的,我想通了。

    我将 jest.conf 文件替换为 jest.config.js 文件:

    //jest.config.js
    module.exports = {
      moduleDirectories: ["node_modules", "src"]
    };
    

    然后我只是运行 jest 就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 2020-08-08
      • 2012-05-13
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多