Nest无法在测试过程中解决UserService的依赖性

时间:2019-09-14 21:43:04

标签: mongoose jestjs nestjs

我正在尝试为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 个答案:

答案 0 :(得分:0)

问题已解决; Private Sub Worksheet_Change(ByVal Target As Excel.Range) If Target.Column = 1 Then Dim lastRow As Long lastRow = Cells(Rows.Count, 1).End(xlUp).Row ActiveSheet.Sort.SortFields.Clear ActiveSheet.Sort.SortFields.Add Key:=Range("A1:A" & lastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal With ActiveSheet.Sort .SetRange Range("A1:J" & lastRow) .Header = xlGuess .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With End If End Sub 包含与USER_MODEL_PROVIDER不同的值,因此USER_MODEL从未被注入。