【问题标题】:Jest: Failed to parse the TypeScript config file开玩笑:无法解析 TypeScript 配置文件
【发布时间】:2022-09-27 16:21:48
【问题描述】:

我正在尝试安装 Jest 以与 Babel 和 Typescript 一起使用。我已经按照shown here 的说明执行了这封信,但我得到了:

错误:Jest:无法解析 TypeScript 配置文件 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) 文件:

sum.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

包.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 部门:npm -i --dev babel-jest @babel/core @babel/preset-env
  • 创建babel.config.js
  • 安装打字稿: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 从 27.5.1 更新到 >=28 时,我遇到了同样的问题。你确定你有关于 .js 文件的错误,而不是 .ts 吗? Error: Jest: Failed to parse the TypeScript config file C:...jest.config.js

标签: typescript npm jestjs babeljs


【解决方案1】:

这对我有用:从 Jest docs https://jestjs.io/docs/next/configuration 创建文件“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"
  }

【讨论】:

    猜你喜欢
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 2021-01-10
    • 2021-08-14
    • 1970-01-01
    • 2019-06-24
    • 2022-07-04
    相关资源
    最近更新 更多