typescript - 如何在 tsconfig.json 上启用 typeRoots 的 typescript/expressjs 应用程序上运行 jest

标签 typescript express jestjs ts-jest

嗯,我有这个项目here ,它包含 typescript 和expressjs。我现在的目标是构建测试,但是当我运行 yarn test (在没有任何标志的情况下运行 jest)时,我收到此错误:

PS C:\Users\joaov\Documents\gittin> yarn test
yarn run v1.22.10
$ jest
Error: Jest: Failed to parse the TypeScript config file C:\Users\joaov\Documents\gittin\jest.config.ts
  TSError: ⨯ Unable to compile TypeScript:
jest.config.ts:1:1 - error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.

1 module.exports = {
  ~~~~~~

    at readConfigFileAndSetRootDir (C:\Users\joaov\Documents\gittin\node_modules\jest-config\build\readConfigFileAndSetRootDir.js:118:13)
    at readConfig (C:\Users\joaov\Documents\gittin\node_modules\jest-config\build\index.js:227:18)
    at readConfigs (C:\Users\joaov\Documents\gittin\node_modules\jest-config\build\index.js:412:26)
    at runCLI (C:\Users\joaov\Documents\gittin\node_modules\@jest\core\build\cli\index.js:220:59)
    at Object.run (C:\Users\joaov\Documents\gittin\node_modules\jest-cli\build\cli\index.js:163:37)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

有人告诉我发生这种情况是因为在我的 tsconfig.json 中启用了 typeRoots 属性。当我评论该行时,测试确实有效,但我想知道如何使 typeRoots 与 Jest 一起工作,因为我需要该本地类型。

为了更快,这些分别是 tsconfig.jsonjest.config.ts:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "dist",
    "rootDir": "src",
    "removeComments": true,
    "strict": true,
    "strictPropertyInitialization": false,
    "typeRoots": ["./src/@types"],
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "exclude": [
    "src/**/*.spec.ts",
    "src/**/*.test.ts",
    "jest.config.ts",
    "ormconfig.js",
    "node_modules"
  ]
}
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

最佳答案

发现我只需要将 ./node_modules/@types 添加到 tsconfig 文件中的 typeRoots 选项即可。

关于typescript - 如何在 tsconfig.json 上启用 typeRoots 的 typescript/expressjs 应用程序上运行 jest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68616038/

相关文章:

axios - 如何使用 Jest 来测试axios拦截器?

javascript - 无法在服务器 NodeJS 上的 Mongo 中创建用户(或基于自定义的角色)

typescript - 如何使用 jest 模拟 typescript 中的外部依赖关系

angular - 如何迭代 Angular 5 组件中的对象

javascript - 为什么我的类型在 React 和 TypeScript 中为 null?

mysql - 当 MySQL 数据发生变化时更新 React 数据

javascript - 在 node.js 中共享对象并避免全局变量

reactjs - 测试 react 组件时出错 - SecurityError

JavaScript/TypeScript : Standard way to keep the cause of an Error

Angular,类型上不存在属性