【问题标题】:Can not run tests with Jest on NestJS无法在 NestJS 上使用 Jest 运行测试
【发布时间】:2020-05-07 19:00:39
【问题描述】:

我正在尝试为我的 GraphQL 端点创建和 e2e 测试。经过一番努力让 Jest 找到测试后,我现在看到 Jest 尝试将测试作为 JavaScript 而不是 TypeScript 运行。这是一个错误输出:

SyntaxError: /server/__tests__/users.e2e-spec.ts: Unexpected token, expected ";" (9:10)

   7 |
   8 | describe('AppController (e2e)', () => {
>  9 |    let app: INestApplication
     |           ^
  10 |    let apolloClient: ApolloServerTestClient
  11 |
  12 |    beforeEach(async () => {

  at Parser.raise (node_modules/@babel/parser/src/parser/location.js:41:63)
  at Parser.unexpected (node_modules/@babel/parser/src/parser/util.js:150:16)
  at Parser.semicolon (node_modules/@babel/parser/src/parser/util.js:123:40)
  at Parser.parseVarStatement (node_modules/@babel/parser/src/parser/statement.js:703:10)
  at Parser.parseStatementContent (node_modules/@babel/parser/src/parser/statement.js:216:21)
  at Parser.parseStatement (node_modules/@babel/parser/src/parser/statement.js:146:17)
  at Parser.parseBlockOrModuleBlockBody (node_modules/@babel/parser/src/parser/statement.js:865:25)
  at Parser.parseBlockBody (node_modules/@babel/parser/src/parser/statement.js:841:10)
  at Parser.parseBlock (node_modules/@babel/parser/src/parser/statement.js:818:10)
  at Parser.parseFunctionBody (node_modules/@babel/parser/src/parser/expression.js:1964:24)

这是来自 package.json 的测试脚本:

"test:e2e": "jest --config ./tests/jest-e2e.json"

还有 Jest 配置文件:

module.exports = {
   roots: ['<rootDir>/src'],
   transform: {
      '^.+\\.tsx?$': 'ts-jest',
   },
   testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
   moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
}

我做错了什么?根据 NestJS 文档,测试应该开箱即用。

【问题讨论】:

    标签: jestjs nestjs


    【解决方案1】:

    按照 ts-jest 页面上的说明解决了我的问题。

    把它放在这里以防有人需要它:

    创建一个笑话配置:

    yarn ts-jest config:init
    

    如果你在tsconfig.json中使用baseUrl,修改配置如下:

    module.exports = {
       preset: 'ts-jest',
       testEnvironment: 'node',
       modulePaths: ['<rootDir>/src'],
    }
    

    我希望 NestJS 文档包含这个。它可以节省我的时间。

    【讨论】:

      【解决方案2】:

      在 tsconfig.json 上配置路径
      在根项目文件夹中创建 jest.config.js

      const { pathsToModuleNameMapper } = require('ts-jest/utils')
      const { compilerOptions } = require('./tsconfig')
      module.exports = {
        preset: 'ts-jest',
        testEnvironment: 'node',
        moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
        modulePaths: [
          '<rootDir>'
        ],
      }
      

      【讨论】:

        猜你喜欢
        • 2021-05-30
        • 2020-11-16
        • 2021-10-15
        • 1970-01-01
        • 1970-01-01
        • 2020-05-15
        • 2022-01-06
        • 2022-01-05
        • 2019-10-21
        相关资源
        最近更新 更多