【问题标题】:Nestjs testing module not found找不到 Nestjs 测试模块
【发布时间】:2020-06-22 07:31:17
【问题描述】:

我使用 Mongdoose 和 Nestjs 创建了一个简单的 REST API。我总共进行了 2 次测试,但都失败了。 测试输出:

失败 src/app/auth/auth.service.spec.ts ● 测试套件无法运行

Cannot find module '@shared/errors' from 'auth.service.ts'

   5 | 
   6 | import { AppLogger } from '../logger/logger';
>  7 | import { Errors } from '@shared/errors';
     | ^
   8 | import { ILoginDto } from './dto/login.dto';
   9 | import { ITokenDto } from './dto/auth.dto';
  10 | import { IUser } from '@user/document/user.doc';

  at Resolver.resolveModule (../../node_modules/jest-resolve/build/index.js:259:17)
  at Object.<anonymous> (auth/auth.service.ts:7:1)

失败 src/app/user/user.service.spec.ts ● 测试套件无法运行

Cannot find module '@shared/errors' from 'user.service.ts'

  1 | import { BadRequestException, Injectable } from '@nestjs/common';
  2 | import { InjectModel } from '@nestjs/mongoose';
> 3 | import { Errors } from '@shared/errors';
    | ^
  4 | import { createMultipleRandom } from '@shared/utils';
  5 | import { Model } from 'mongoose';
  6 | import { AppLogger } from '../logger/logger';

  at Resolver.resolveModule (../../node_modules/jest-resolve/build/index.js:259:17)
  at Object.<anonymous> (user/user.service.ts:3:1)

测试套件:2 个失败,总共 2 个 测试:共 0 快照:共 0 个 时间:2.751s 运行所有测试套件。

tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "paths": {
      "@app/*": ["src/app/*"],
      "@auth/*": ["src/app/auth/*"],
      "@config/*": ["config/*"],
      "@logger/*": ["src/app/logger/*"],
      "@shared/*": ["src/app/shared/*"],
      "@user/*": ["src/app/user/*"],
    }
  },
  "include": [
    "src/**/*"
  ],

  "exclude": ["node_modules", "dist"]
}

auth.service.spec.ts:

import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
  let service: AuthService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [AuthService],
    }).compile();

    service = module.get<AuthService>(AuthService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});

在@shared/errors.ts 我只是导出一个常量变量。既然它不是一个模块,我应该如何在测试中导入它?我该如何解决这个问题?

【问题讨论】:

    标签: jestjs nestjs


    【解决方案1】:

    当您使用 typescript 的路径映射时,您还需要使用映射路径更新您的 jest 配置。您的笑话配置需要添加以下内容:

    {
      ...
      "moduleNameMapper": {
        "^@Shared/(.)*$": "<rootDir>/src/app/shared/$1"
      }
    }
    

    假设您的&lt;rootDir&gt; 设置为. 而不是./src。你可以find more info on it here

    【讨论】:

    • 谢谢,这对我有用 :) 我现在正在尝试测试使用 Mongoose 模型的服务,您对此也有一些提示吗?我认为这个docs.nestjs.com/techniques/mongodb#testing 会帮助我
    • 您需要一个模拟模型来管理它。你可以see some examples here
    • 我像示例中一样模拟了模型,但我现在遇到了另一个问题。它说,'DatabaseConnection' 在 MongooseModule 上下文中不可用。既然我做了模拟,为什么我需要一个连接呢?
    • 这会让我相信您的代码中的某处仍在使用数据库连接。没有看到正在发生的事情,就不能轻易回答。听起来像是完全模拟的某些模型,但又不能确定
    • 我发现了问题。在“AuthService”中,我注入了“UserService”,它使用了 MongooseModule.forFeature(...)。所以测试文件中缺少 MongooseModule。在我导入了 MondooseModule.forRoot(..) 的模块后,它就起作用了。再次感谢。
    【解决方案2】:

    这里是jest-path-resolving问题的详细配置。

    moduleNameMapper 中定义的键将被替换为它们的值。

    例如,当 jest 看到 '@resources' 时,会将其替换为 'src/resources'

    (使用索引文件有很大帮助)

    package.json 中的 Jest 配置

     "jest": {
        "moduleFileExtensions": [
          "js",
          "json",
          "ts"
        ],
        "rootDir": "src",
        "moduleNameMapper": {
          "@resources": "<rootDir>/resources",
          "@shared": "<rootDir>/shared",
          "@email": "<rootDir>/email",
          "@auth": "<rootDir>/auth",
          "@config": "<rootDir>/config",
          "@database": "<rootDir>/database"
        },
        "testRegex": ".*\\.spec\\.ts$",
        "transform": {
          "^.+\\.(t|j)s$": "ts-jest"
        },
        "collectCoverageFrom": [
          "**/*.(t|j)s"
        ],
        "coverageDirectory": "../coverage",
        "testEnvironment": "node"
      }
    
    

    打字稿配置

     "paths": {
          "@resources/*": ["src/resources/*"],
          "@resources": ["src/resources"],
          "@shared/*": ["src/shared/*"],
          "@shared": ["src/shared"],
          "@email/*": ["src/email/*"],
          "@email": ["src/email"]
        }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-18
      • 2021-08-12
      • 2021-12-23
      • 2020-08-02
      • 1970-01-01
      • 2022-12-24
      • 2018-05-25
      • 2019-08-06
      相关资源
      最近更新 更多