gpt4 book ai didi

typescript - Jest : Failed to parse the TypeScript config file

转载 作者:行者123 更新时间:2023-12-05 05:45:46 25 4
gpt4 key购买 nike

我正在尝试安装 Jest 以便与 Babel 和 Typescript 一起使用。我已按照说明进行操作 shown here不折不扣,但我得到:

Error: Jest: Failed to parse the TypeScript config file C:...jest.config.js`

...当我运行 npm run test 时。

jest.config.ts 的内容是:

export default {
//lots of commented-out stuff in here - nothing at all uncommented
}

这是我执行的具体步骤:

  • 初始化项目 - npm init -y
  • 安装 Jest - npm -i --save-dev jest
  • 制作一个脚本(sum.js)和一个测试(sum.test.js)文件:

求和.js:

function sum(a, b) {
return a + b;
}
module.exports = sum;

sum.test.js

const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
  • test命令添加到package.json:

package.json:

{
"name": "jest-learn",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.17.5",
"@babel/preset-env": "^7.16.11",
"@babel/preset-typescript": "^7.16.7",
"babel-jest": "^27.5.1",
"jest": "^27.5.1"
}
}

此时,如果我运行 yarn test,我的测试运行并顺利通过。问题是当我尝试引入 Babel 和 Typescript 时。 步骤继续:

  • 安装 Babel deps: npm -i --dev babel-jest @babel/core @babel/preset-env
  • 创建babel.config.js
  • 安装 Typescript:npm -i --dev @babel/preset-typescript
  • @babel/preset-typescript添加到babel.config.js:

babel.config.js:

module.exports = {
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
'@babel/preset-typescript',
],
};

现在,当我运行 npm run test 时,出现了上述错误。我做错了什么?

最佳答案

这对我有用:从 Jest 文档 [https://jestjs.io/docs/next/configuration][1] 创建文件“jest.config.ts”并将其添加到源目录,内容如下:

/** @type {import('jest').Config} */
const config = {
verbose: true,
};

module.exports = config;

然后,确保将文件包含在您的 tsconfig.json 文件中:

...
"include": ["./src/**/*.tsx", "./src/**/*.ts", "src/jest.config.ts"]

还要确保您在项目中安装了“jest”、“ts-jest”和“ts-node-dev”模块:

...
},
"devDependencies": {
"@faker-js/faker": "^7.5.0",
"@types/express": "^4.17.14",
"@types/jest": "^29.0.3",
"@types/uuid": "^8.3.4",
"jest": "^29.0.3",
"nodemon": "^2.0.20",
"ts-jest": "^29.0.2",
"ts-node-dev": "^2.0.0",
"typescript": "^4.8.3"
}

package.json 中的 jest 转换配置脚本如下所示:

"jest": {
"transform": {
".(ts|tsx)": "ts-jest"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
]
},

关于typescript - Jest : Failed to parse the TypeScript config file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71297895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com