使用 .ts 文件(TypeScript)配置 Jest 全局测试设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/48318230/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Configure Jest global tests setup with .ts file (TypeScript)
提问by Aleksei Semidotskii
I am using ts-jest (Jest and TypeScript) and want to configure some global setup for all test suites (initialize test database).
我正在使用 ts-jest(Jest 和 TypeScript)并想为所有测试套件配置一些全局设置(初始化测试数据库)。
I found that there is globalSetupoptions in jest configuration:
我发现globalSetup在 jest 配置中有选项:
"jest": {
    "globalSetup": "./jest-config.js"
}
but only .jsfile can be used for setup. I want to use .tsfile because all my code
including code for setup in TypeScript.
但只能使用.js文件进行设置。我想使用.ts文件,因为我所有的代码都包括在 TypeScript 中设置的代码。
How can I achieve this?
我怎样才能做到这一点?
采纳答案by Aleksei Semidotskii
I found a solution.
我找到了解决办法。
My initial project structure was:
我最初的项目结构是:
.
|--src
|  |--service.ts
|--tests
|  |--service.test.ts
|--dist
|--tsconfig.json 
|--package.json
Jest configuration in package.json:
package.json 中的 Jest 配置:
"jest": {
  "globals": {
    "ts-jest": {
      "tsConfigFile": "tsconfig.json"
    }
  },
  "moduleFileExtensions": ["ts","js"],
  "transform": {
    "^.+\.(ts|tsx)$": "./node_modules/ts-jest/preprocessor.js"
  },
  "testMatch": [
    "**/tests/**/*.test.(ts|js)"
  ],
  "testEnvironment": "node"
}
With this configuration ts-jestperform in memory transpiling of the .ts files. 
I have outDiroption in compilerOptionsof my tsconfig.json, but nothing is written in that outDir and because I cann't use transpiled jest-config.js
使用此配置ts-jest在内存中执行 .ts 文件的转换。我有outDirincompilerOptions的选项tsconfig.json,但在那个 outDir 中什么也没写,因为我不能使用转译的 jest-config.js
Then I move tests folder in src and change Jest config. New structure of the project is:
然后我在 src 中移动测试文件夹并更改 Jest config。该项目的新结构是:
.
|--src
|  |--service.ts
|  |--tests
|     |--service.test.ts
|     |--jest-config.ts
|--dist
|--tsconfig.json 
|--package.json
New Jest config is:
新的 Jest 配置是:
"jest": {
  "globalSetup": "./dist/tests/jest-config.js",
  "moduleFileExtensions": ["ts", "js", "json"],
  "testMatch": [
    "**/dist/**/*.test.js"
  ],
  "testEnvironment": "node"
}
Now I can use jest-config.js for global setup in Jest.
现在我可以在 Jest 中使用 jest-config.js 进行全局设置。
Addition
添加
- Jest setup file (in my example jest-config.js) must export one async function: - module.exports = async function() { ... }
- Before running the tests, you need to compile source .ts files. 
- Jest 设置文件(在我的示例 jest-config.js 中)必须导出一个异步函数: - module.exports = async function() { ... }
- 在运行测试之前,您需要编译源 .ts 文件。 

