【问题标题】:Nest.js is unable to resolve Mongoose model dependency in unit testNest.js 在单元测试中无法解析 Mongoose 模型依赖
【发布时间】:2020-04-14 10:14:40
【问题描述】:

在为控制器编写单元测试时,Nest 无法解析我的 Mongoose 模型依赖:

Nest 无法解析 UsersService (?) 的依赖关系。请做出来 确保索引 [0] 处的参数 USER_MODEL 在 _RootTestModule 上下文。

Potential solutions:
- If USER_MODEL is a provider, is it part of the current _RootTestModule?
- If USER_MODEL is exported from a separate @Module, is that module imported within _RootTestModule?
  @Module({
    imports: [ /* the Module containing USER_MODEL */ ]
  })

我的模型是通过 users.service.ts 中的服务构造函数注入的:

import { IUserModel } from './interfaces';
import { Model } from 'mongoose';
import { USER_MODEL } from './constants/users.constants';

@Injectable()
export class UsersService {

  constructor (
    @Inject(USER_MODEL)
    private readonly userModel: Model<IUserModel>,
  ) {}

  ...
}

我的测试定义为:

const mockUserModel = {};

describe('Users Controller', () => {
  let usersController: UsersController;
  let usersService: UsersService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UsersController],
      providers: [
        {
          provide: getModelToken(USER_MODEL),
          useValue: mockUserModel,
        },
        UsersService,
      ],
    }).compile();

    usersController = module.get<UsersController>(UsersController);
    usersService = module.get<UsersService>(UsersService);
  });

  it('should define user controller and service', () => {
    expect(usersController).toBeDefined();
    expect(usersService).toBeDefined();
  });
});

所有这些类都定义在同一个模块中。我不太确定 Nest 在寻找什么。我正在关注https://docs.nestjs.com/fundamentals/testing 的指南,并且还查看了几个较旧的 Github 问题。

我还尝试创建一个自定义类提供程序,定义如下:https://docs.nestjs.com/fundamentals/custom-providers 来提供类型化的 Mongoose 模型,但返回了相同的错误。

谁能帮帮我?

【问题讨论】:

    标签: node.js nestjs


    【解决方案1】:

    如果您使用的是@Inject(USER_MODEL),那么您需要在测试中使用provide: USER_MODEL。如果您使用@InjectModel() 而不是原始@Inject(),则getModelToken 实用程序方法是必需的。

    【讨论】:

    • 谢谢,但我应该如何创建测试模块?你有任何示例代码或文档吗?
    • 我有an entire repository 专门用于测试示例。随意检查出来。您的设置基本正确,只是为您的模型提供了错误的mock token
    • 完美。非常感谢您提供的精彩文档!
    • 查看存储库,我没有看到任何关于 Passport 和使用 AuthGuards 测试控制器的信息。搜索并没有找到很多示例。过去,我选择了 E2E 测试并设置单独的数据库进行测试。如果您有其他方法,我将不胜感激。
    • 明白了。我想我总是可以构造一个假用户对象来分配给请求并使用 node-mocks-http 模拟请求以传递给这些函数。感谢您的提示!
    猜你喜欢
    • 2020-05-27
    • 2020-10-30
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2022-01-21
    • 2016-11-12
    • 1970-01-01
    相关资源
    最近更新 更多