Nest.js 无法解决单元测试中的 Mongoose 模型依赖关系

Bra*_*don 3 node.js nestjs

当为控制器编写单元测试时,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 */ ]
  })
Run Code Online (Sandbox Code Playgroud)

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

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 */ ]
  })
Run Code Online (Sandbox Code Playgroud)

我的测试定义为:

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>,
  ) {}

  ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

谁能帮我吗?

Jay*_*iel 6

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