next.js 即使在正确配置之后,Jest仍无法解析JSX语法[重复]

xxls0lw8  于 2022-11-23  发布在  Jest
关注(0)|答案(1)|浏览(196)

此问题在此处已有答案

jest unexpected token when importing css(5个答案)
11天前关闭。
我已经开始了一个新的Next项目,并按照文档的要求配置了jest和测试库。
由于语法错误,测试失败,由于某种原因ts-jest无法解析stayles. container。
这种行为的原因是什么?如何解决?
Next全新安装附带了默认索引页的一小部分:

import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'

export default function Home() {
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

测试文件(索引.test.tsx):

import Home from '../pages/index';
import { screen, render } from '@testing-library/react';

test("rendering the base component", () => {
    render(<Home />)
});

jest.config.js:

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
};

Package.json:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "test": "jest"
  },
  "dependencies": {
    "@types/node": "18.11.9",
    "@types/react": "18.0.25",
    "@types/react-dom": "18.0.8",
    "eslint": "8.27.0",
    "eslint-config-next": "13.0.2",
    "jest-environment-jsdom": "^29.3.1",
    "next": "13.0.2",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "typescript": "4.8.4"
  },
  "devDependencies": {
    "@testing-library/react": "^13.4.0",
    "@types/jest": "^29.2.2",
    "ts-jest": "^29.0.3"
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "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": "react-jsx",
    "incremental": true
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

错误详细信息:

C:\Users\Daniel\Desktop\nextJSProjects\my-app\styles\Home.module.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){.container {
                                                                                  ^

SyntaxError: Unexpected token '.'
mwg9r5ms

mwg9r5ms1#

这个错误表示JestJs无法解析CSS模块。您应该模拟CSS模块,请参阅模拟CSS模块

npm install --save-dev identity-obj-proxy

jest.config.js

module.exports = {
  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/__mocks__/fileMock.js',
    '\\.(css|less)$': 'identity-obj-proxy',
  },
};

相关问题