在 TypeScript 中测试和运行程序的问题

问题描述 投票:0回答:1

我一直在用 TypeScript 和 Express 制作一个应用程序。现在我想做单元测试(有点晚了,我知道)并发现了这个问题:

  1. 要运行测试,.ts 文件内的导入不需要具有文件扩展名 .js
  2. 要编译测试的代码,.ts 文件内的导入需要具有文件扩展名 .js

我缺少一些配置吗?

jest.config.js

/** @type {import('ts-jest').JestConfigWithTsJest} */
// module.exports = {
//   preset: 'ts-jest',
//   testEnvironment: 'node',
// };

export default {
  preset:"ts-jest",
  testEnvironment:"node",
  testMatch: [
    '**/*.test.ts' // Solo ejecutar archivos .test.js
  ]
}

tsconfig.json

{
   "compilerOptions":{
    "target": "es2016", 
    "module": "Node16",
    "rootDir": "./src", 
    "sourceMap": true, 
    "outDir": "./dist",
    "removeComments": false,    
    "noEmitOnError": false, 
    "esModuleInterop": true, 
    "forceConsistentCasingInFileNames": true,  
    "strict": true, 
    "skipLibCheck": true 
    }
}

我做了什么:

  1. 消除 .ts 文件中的 .js 扩展名
  2. 根据我在
    here
    读到的内容,将
    moduleResolution
    值更改为"bundle",但编译器说
    moduleResolution
    不能具有该值
typescript jestjs ts-jest
1个回答
0
投票

我找到了解决方案。 似乎您必须停用 tsconfig 文件中的选项

"module": "ES2022"
才能让您执行没有文件扩展名的文件(同时将
"module"...
保留在 package.json 中)。 这也产生了另一个问题,你不能再导入 npm 安装的包了...所以你还必须在 tsconfig 文件中使用这个选项
"moduleResolution": "node"

简历 nivel 5 taringuero:

//"module": "ES2022" "moduleResolution": "node" 

© www.soinside.com 2019 - 2024. All rights reserved.