如何修复 Jest 错误 - 测试套件无法运行

问题描述

我有一个项目,它使用纱线来处理 React、TypeScript、Next.js 和 Jest。

如果我尝试测试,它会失败并显示以下错误消息。

FAIL src/components/Dashboard/Report.test.tsx

Test suite Failed to run

    Your application tried to access src,but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.

    required package: src (via "src/components/CustomLink")
    required by: /home/user/project/src/components/Dashboard/Report

我在 CustomLink.tsx 文件中导入了 Report.tsx 文件

import { CustomLink } from 'src/components/CustomLink';

jest.config.js 文件在这里

module.exports = {
  roots: ['<rootDir>/src','<rootDir>/pages','<rootDir>/__tests__/pages'],globalSetup: '<rootDir>/__tests__/util/globalSetup.ts',setupFilesAfterEnv: ['<rootDir>/__tests__/util/setup.ts'],transform: {
    '\\.[jt]sx?$': 'babel-jest','\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/__tests__/util/fileMock.js','\\.(gql|graphql)$': 'jest-transform-graphql',},modulefileExtensions: ['ts','tsx','js','jsx','json','node'],clearMocks: true,};

tsconfig.json 文件在这里

{
  "compilerOptions": {
    "baseUrl": ".","target": "esnext","lib": ["dom","dom.iterable","esnext"],"allowJs": true,"skipLibCheck": true,"strict": true,"forceConsistentCasingInFileNames": true,"noEmit": true,"esModuleInterop": true,"module": "esnext","moduleResolution": "node","resolveJsonModule": true,"isolatedModules": true,"jsx": "preserve","exclude": ["node_modules"],"include": ["next-env.d.ts","**/*.ts","**/*.tsx",".env"]
}

我通过在 jest.config.js 文件添加 moduleNameMapper 解决了这个问题。

  moduleNameMapper: {
    'src/(.*)': '<rootDir>/src/$1','__tests__/(.*)': '<rootDir>/__tests__/$1',

但是我还有一个问题是 jest 找不到 graphql 生成文件

import { ReportType } from 'graphql/types.generated';
Test suite Failed to run

    Qualified path resolution Failed - none of the candidates can be found on the disk.

    Source path: /home/user/project/.yarn/cache/graphql-npm-15.5.0-65986c56be-789cdcb069.zip/node_modules/graphql/types.generated

我正在使用 Graphql Apollo 客户端,因此它会通过 yarn gql 自动生成 graphql 类型文件

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)