繁体   English   中英

在 Next.js 上使用 jest 找不到模块错误

[英]Cannot find module error using jest on Next.js

你好,我在我的 nextjs 应用程序上让 jest 工作时遇到了一些麻烦,当我使用脚本“jest”时,我总是执行失败,结果是这样的


 FAIL  __tests__/index.test.tsx
  ● Test suite failed to run

    Cannot find module '@components/Layout' from 'pages/404.tsx'

    Require stack:
      pages/404.tsx
      __tests__/index.test.tsx

    > 1 | import { Layout } from '@components/Layout'
        |                                            ^
      2 | import { ContainerChild } from '@components/Container'
      3 | import { Button } from '@castia/components.ui.button'
      4 | import Image from 'next/image'

      at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:491:11)
      at Object.<anonymous> (pages/404.tsx:1:44)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.31 s
Ran all test suites.

这是我的测试文件

import renderer from "react-test-renderer";
import NotFound from "../pages/404";

describe("404 NotFound page", () => {
  const tree = renderer.create(<NotFound />).toJSON();
  expect(tree).toMatchSnapshot();
});

这是我的组件文件

import { Layout } from '@components/Layout'
import { ContainerChild } from '@components/Container'
import Image from 'next/image'

import styles from '@styles/404.module.scss'

const metaTags = {
  title: 'Castia | 404',
  description: 'No encontramos la página que buscabas',
}

export default function NotFoundPage() {
  return (
    <Layout metaTags={metaTags}>
      <ContainerChild composition={'default'}>
        <div className={styles.error404}>
          <div>
            <Image
              src="/assets/image/error-404.png"
              alt="No encontramos la página que buscabas"
              width={475}
              height={304}
            />
          </div>

          <h3>¡Ups! No encontramos la página que buscabas.</h3>
          <p>
            Revisa que hayas escrito correctamente el enlace o regresa a la
            página principal.
          </p>
          <div className={styles.containerBtn}>

          </div>
        </div>
      </ContainerChild>
    </Layout>
  )
}

我的 jest.config.js 文件配置如下

const nextJest = require('next/jest')
const createJestConfig = nextJest({
  dir: './',
})
const customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleNameMapper: {
    '^@/components/(.*)$': '<rootDir>/components/$1',
    '^@/pages/(.*)$': '<rootDir>/pages/$1',
    '^@/ui/(.*)$': '<rootDir>/ui/$1',
    '^@/api/(.*)$': '<rootDir>/api/$1',
    '^@/components/(.*)$': '<rootDir>/components/$1',
    '^@/context/(.*)$': '<rootDir>/context/$1',
    '^@/styles/(.*)$': '<rootDir>/styles/$1',
    '^@/lib/(.*)$': '<rootDir>/lib/$1',
    '^@/hooks/(.*)$': '<rootDir>/hooks/$1',
    '^@/utils/(.*)$': '<rootDir>/utils/$1',
  },
  testEnvironment: 'jest-environment-jsdom',
}

module.exports = createJestConfig(customJestConfig)

和我的 tsconfig.json 像这样

{
  "compilerOptions": {
    "target": "es6",
    "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",
    "incremental": true,
    "baseUrl": ".",
    "paths": {
      "@ui/*": ["ui/*"],
      "@api/*": ["pages/api/*"],
      "@components/*": ["components/*"],
      "@context/*": ["context/*"],
      "@styles/*": ["styles/*"],
      "@lib/*": ["lib/*"],
      "@hooks/*": ["hooks/*"],
      "@utils/*": ["utils/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

但我不知道为什么这会发生在我身上

您似乎忘记在 tsconfig.json 中为“pages”目录添加绝对路径映射。

尝试将此添加到您的 tsconfig.json

{...
"paths": {
   ... other paths mappings
  "@pages/*": ["pages/*"],
...
}

我认为它应该是你的组件文件中的“@/components”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM