Nest 在测试期间无法解析 UserService 的依赖关系

Posted

技术标签:

【中文标题】Nest 在测试期间无法解析 UserService 的依赖关系【英文标题】:Nest can't resolve dependency of UserService during testing 【发布时间】:2020-01-16 06:22:26 【问题描述】:

我正在尝试为 UserService 编写一个单元测试,它具有 Mongoose 模型作为依赖项,但是当我运行测试时它无法解决。

user.module.ts

import  Module  from '@nestjs/common';
import  DatabaseModule  from '../database/database.module';
import  UserService  from './user.service';
import userProviders from './providers';

@Module(
  imports: [DatabaseModule],
  providers: [UserService, ...userProviders],
  exports: [UserService],
)
export class UserModule 

user.provider.ts

import  Connection  from 'mongoose';

import  UserSchema  from '../schemas/user.schema';
import  USER_MODEL_PROVIDER, DB_PROVIDER  from '../../../constants/database';
import  Provider  from '@nestjs/common';
import  USER_MODEL  from '../../../constants/models';

export const userProvider: Provider = 
  provide: USER_MODEL_PROVIDER,
  useFactory: (connection: Connection) =>
    connection.model(USER_MODEL, UserSchema),
  inject: [DB_PROVIDER],
;

user.service.ts

import  Injectable  from '@nestjs/common';
import  InjectModel  from '@nestjs/mongoose';
import  Model  from 'mongoose';
import  User  from './interfaces/user.interface';
import  USER_MODEL  from '../../constants/models';
import  CreateUserDto  from './dto/create-user.dto';
import  UpdateUserDto  from './dto/update-user.dto';

@Injectable()
export class UserService 
  constructor(
    @InjectModel(USER_MODEL)
    private readonly userModel: Model<User>,
  ) 

  async getUsers(): Promise<User[]> 
    return this.userModel.find().exec();
  

  async getUser(userId: any): Promise<User> 
    return this.userModel.findById(userId).exec();
  

  async addUser(dto: CreateUserDto): Promise<User> 
    return new this.userModel(dto).save();
  

  async updateUser(userId: any, dto: UpdateUserDto): Promise<User> 
    return this.userModel.findByIdAndUpdate(userId, dto, 
      new: true,
    );
  

user.service.spec.ts

import  Test  from '@nestjs/testing';
import  USER_MODEL  from '../../constants/models';
import  User  from './interfaces/user.interface';
import  UserService  from './user.service';
import  getModelToken  from '@nestjs/mongoose';
import  Model  from 'mongoose';
import userProviders from './providers';
import  DatabaseModule  from '../database/database.module';

describe('UserService', () => 
  let userService: UserService;
  let userModel: Model<User>;
  const token = getModelToken(USER_MODEL);

  beforeAll(async () => 
    const userModule = await Test.createTestingModule(
      imports: [DatabaseModule],
      providers: [UserService, ...userProviders],
    ).compile();

    userService = userModule.get<UserService>(UserService);
    userModel = userModule.get(token);
  );

  it('should get all users', async () => 
    const users = await userService.getUsers();
    expect(users).toEqual([]);
  );
);

如何注入模型以便在测试阶段可用?

【问题讨论】:

【参考方案1】:

问题已解决; USER_MODEL_PROVIDER 包含的值与 USER_MODEL 不同,因此从未注入 UserSchema

【讨论】:

以上是关于Nest 在测试期间无法解析 UserService 的依赖关系的主要内容,如果未能解决你的问题,请参考以下文章

NestJS 错误:错误:Nest 无法解析 AuthService (?, JwtService) 的依赖项

当我使用 Bazel Test 时,Nest 无法解析 RootTestModule 上下文中的依赖关系

Nest.js 无法解决对 TestingModule 的循环依赖

Nest 无法解析 PhotoService 的依赖关系(?)

Nest 无法解析 UserModel 的依赖项(?)

Nest 无法解析 RabbitMQService 服务的依赖关系