我突然遇到了这个错误。
当我使用代码时,它能正常工作,但是在使用 Jest 进行测试时,它就会出现。......................................................................................................................................................................................................................................................................................................................................................................................................................
详细信息:
C:\node_modules\react-leaflet\lib\index.js
:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { us
eMap, useMapEvent, useMapEvents } from './hooks.js';
^^^^^^
SyntaxError: Unexpected token 'export'
9 | } from 'react-leaflet';
10 | import { private } from 'private';
> 11 |
| ^
这是我的Jest配置
module.exports = {
moduleNameMapper: {
// Resolve .css and similar files to identity-obj-proxy instead.
'.+\\.(css|styl|less|sass|scss)$': 'identity-obj-proxy',
// Resolve .jpg and similar files to __mocks__/file-mock.js
'.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/__mocks__/file-mock.js',
},
clearMocks: true,
coverageDirectory: 'coverage',
// In jest.config.js add (if you haven't already)
setupFilesAfterEnv: ['./src/setupTests.js'],
coverageProvider: 'v8',
globals: {
'ts-jest': {
isolatedModules: true,
},
},
rootDir: '.',
moduleDirectories: ['node_modules', 'src', 'utils'],
testEnvironment: 'jsdom',
testTimeout: 20000,
roots: ['<rootDir>/src'],
testMatch: [
'**/__tests__/**/*.+(ts|tsx|js)',
'**/?(*.)+(spec|test).+(ts|tsx|js)',
],
transform: {
'^.+\\.js?$': 'babel-jest',
'^.+\\.(t|j)sx?$': ['@swc/jest'],
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
transformIgnorePatterns: [`/node_modules/(?!${esModules}')`],
};
TsConfig
"include": [
"src/**/*.ts",
"src/**/*.tsx",
],
"exclude": [
"node_modules",
"dist"
],
"compilerOptions": {
"target": "es2015",
"module": "esnext",
"declaration": true,
"lib": [
"es2021",
"es2017",
"es2015",
"dom",
"ESNext"
],
"allowJs": false,
"jsx": "react-jsx",
"sourceMap": true,
"outDir": "dist",
"rootDir": "src",
"removeComments": true,
"strict": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"isolatedModules": true,
"noEmit": true,
"baseUrl": "src",
"paths": {
"test-utils": [
"./utils/test-utils"
]
}
}
}
.Bablerc & config
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
module.exports = {
presets: [
[
'@parcel/babel-preset-env',
{
targets: {
esmodules: true,
},
},
],
],
};
有什么可能会导致这种情况发生,还是我漏掉了其他的东西?
ts-jest
,你需要在 Jest 中为 TS 文件使用特殊的转换器和预设。 - casraf