我正在使用TypeScript编写Next.js项目,并使用Jest和React Testing Lib进行测试。然而,当我导入 rehype-raw 组件时,遇到了SyntaxError: Cannot use import statement outside a module。
据我所知,Jest不支持ES6,因此node_modules可能需要转换。可以使用 transformIgnorePatterns
进行配置。例如,如果使用 "transformIgnorePatterns": ["node_modules/(?!rehype-raw)/"]
,则会允许转换 rehype-raw
,但不包括其他模块。由此解决此错误。
然而,这对我来说没有用。但我不知道为什么,也不知道如何解决。我附上了我的 error output、jest.config.js 和 babel.rc 文件。
错误输出
FAIL test/pages/companies/[id].test.tsx
● Test suite failed to run
Jest encountered an unexpected token
[...]
Details:
/path/frontend-job/node_modules/rehype-raw/index.js:7
import {raw} from 'hast-util-raw'
^^^^^^
SyntaxError: Cannot use import statement outside a module
3 | import Image from 'next/image';
4 | import { Remark } from 'react-remark';
> 5 | import rehypeRaw from 'rehype-raw';
| ^
6 | import rehypeSanitize from 'rehype-sanitize';
7 | import { logError } from '@utils/logger';
8 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (components/markdown/JobMarkdown.tsx:5:1)
jest.config.js
const { resolve } = require('path');
module.exports = {
roots: ['<rootDir>'],
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json', 'node'],
setupFiles: ['<rootDir>/test/setup.js'],
testPathIgnorePatterns: ['<rootDir>[/\\\\](node_modules|.next)[/\\\\]'],
transform: {
'^.+\\.(ts|tsx)$': 'babel-jest',
},
transformIgnorePatterns: [
'node_modules/(?!rehype-raw)/',
],
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
moduleNameMapper: {
// Force mocks: https://github.com/facebook/jest/issues/4262
'@api/axios': '<rootDir>/test/__mocks__/axios.js',
// Normal module aliases
'\\.(css|less|sass|scss)$': 'identity-obj-proxy',
'\\.(gif|ttf|eot|svg|png)$': '<rootDir>/test/__mocks__/fileMock.js',
'^@test/(.*)$': resolve(__dirname, './test/$1'),
'^@test/faker/(.*)$': resolve(__dirname, './test/faker/$1'),
'^@components/(.*)$': resolve(__dirname, './components/$1'),
'^@pages/(.*)$': resolve(__dirname, './pages/$1'),
'^@utils/(.*)$': resolve(__dirname, './utils/$1'),
'^@api/(.*)$': resolve(__dirname, './api/$1'),
'^@store/(.*)$': resolve(__dirname, './store/$1'),
},
testEnvironment: 'jsdom',
};
babel.rc
{
"presets": ["next/babel"]
}