如果我使用import/exportES6,那么我的所有测试都会失败并显示错误:
意外的保留字
我将我的测试对象转换为使用旧学校IIFY语法,突然我的测试通过了.或者,采用更简单的测试用例:
var Validation = require('../src/components/validation/validation');//PASS
//import * as Validation from '../src/components/validation/validation'//FAIL
Run Code Online (Sandbox Code Playgroud)
同样的错误.显然这里导入/导出存在问题.使用ES5语法重写我的代码只是为了让我的测试框架感到满意是不切实际的.
我有巴贝尔开玩笑.我尝试了github问题的各种建议.不行,到目前为止.
"scripts": {
"start": "webpack-dev-server",
"test": "jest"
},
"jest": {
"testPathDirs": [
"__tests__"
],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testFileExtensions": ["es6", "js"],
"moduleFileExtensions": ["js", "json", "es6"]
},
Run Code Online (Sandbox Code Playgroud)
{
"presets": ["es2015", "react"],
"plugins": ["transform-decorators-legacy"]
}
Run Code Online (Sandbox Code Playgroud)
有没有解决这个问题?
我试图解决这个问题已经走进了死胡同。我正在使用以下 TypeScript 配置:
{
"compilerOptions": {
"module": "es2022",
"moduleResolution": "nodenext",
"target": "es2017",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"noImplicitAny": true,
"outDir": "./dist",
"rootDir": "./src",
"typeRoots": [
"./src/types", "./node_modules/@types"],
"allowJs": true,
"strictFunctionTypes": true,
"noImplicitReturns": true
},
"include": ["./src/**/*"],
"exclude": ["node_modules"],
"ts-node": {
"esm": true,
"experimentalSpecifierResolution": true
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的, moduleResolution 设置为nodenext,因此我必须在导入时显式添加文件扩展名,如下所示: import ServerError from '../models/Errors/ServerError.js';。否则,我会收到一条错误消息,指出找不到该模块。
一切工作正常,但是当我启动测试时出现错误: Cannot find module '../models/Errors/ServerError.js' from '../src/services/usersService.ts'。所以基本上 jest 试图找到文件 ServerError.js,但它不存在,因为所有文件都有 .ts 扩展名,所以它应该是 ServerError.ts。如果我尝试将文件中的 .js 更改为 .ts,我也会收到错误。
由于这个问题,我无法完成我的任务,因此我将不胜感激。