node.js - 如何通过 typescript 使用 jest 配置

标签 node.js typescript jestjs

我正在使用nestjs。
在运行所有测试之前需要运行迁移。在所有运行测试之后,nedd 运行清除测试模式。
如果我在 test/config/setup.js package.json 中使用 javascript 设置文件,则一切正常。
但如果我使用 typescript 文件就不起作用。

    "globals": {
      "ts-jest": {
        "tsConfigFile": "tsconfig.json"
      }
    },
    "globalSetup": "./config/setup.ts",
    "globalTeardown": "./config/teardown.ts",
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "./test",
    "testRegex": ".spec.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }

测试/config/setup.ts

import * as dotenv from 'dotenv'; // errors when run jest

module.exports = async () => {
    dotenv.config({path: '.env.test'});
};

错误

/home/jashka/job/projects/project-name/test/config/setup.ts:1
(function (exports, require, module, __filename, __dirname) { import * as dotenv from 'dotenv';
                                                                     ^

SyntaxError: Unexpected token *
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:656:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)
    at Module.require (internal/modules/cjs/loader.js:636:17)
    at require (internal/modules/cjs/helpers.js:20:18)

最佳答案

这是我的 jest.config.js 文件,它与 .ts 设置文件一起使用。添加 '^.+\\.tsx?$': 'ts-jest', 来转换您的 .ts 文件并将 tsConfigFile 更改为tsConfig

module.exports = {
  setupFiles: ['<rootDir>/tests/unit/setup.ts'],
  globalSetup: '<rootDir>/tests/unit/globalSetup.ts',
  globalTeardown: '<rootDir>/tests/unit/globalTeardown.ts',
  moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx'],
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
    '^.+\\.tsx?$': 'ts-jest',
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },
  testMatch: [
    '<rootDir>/tests/unit/**/(*.)spec.(js|jsx|ts|tsx)',
  ],
  globals: {
    'ts-jest': {
      babel: true,
      tsConfig: "tsconfig.json",
    }
  }
};

关于node.js - 如何通过 typescript 使用 jest 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54185203/

相关文章:

reactjs - 为什么我的 Jest 测试在使用 Typescript 的 React Native 中失败?

node.js - ReactJS 中的路由

jquery - jquery ui datetimepicker 不起作用(node.js + ejs + Express)

javascript - Node.js - 更改导出整数的值

javascript - react setState 函数

typescript - 推断链式函数的 ReturnType<>

unit-testing - TypeScript 中的单元测试

reactjs - 在 Jest 测试中,它说 withRouter () 不是函数

javascript - 如何比较 Jest 中的 ENOENT 错误?

javascript - 忽略负鼠断路器中的 HTTP 404 错误