如何在NestJS(Typeorm和Jest)中模拟存储库,服务和控制器

时间:2020-03-12 10:54:59

标签: node.js typescript jestjs nestjs typeorm

我是打字稿新手。我的Nestjs项目应用就是这样。我试图使用存储库模式,所以我将业务逻辑(服务)和持久性逻辑(存储库)分开了

UserRepository

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { UserEntity } from './entities/user.entity';

@Injectable()
export class UserRepo {
  constructor(@InjectRepository(UserEntity) private readonly repo: Repository<UserEntity>) {}

  public find(): Promise<UserEntity[]> {
    return this.repo.find();
  }
}

UserService

import { Injectable } from '@nestjs/common';
import { UserRepo } from './user.repository';

@Injectable()
export class UserService {
  constructor(private readonly userRepo: UserRepo) {}

  public async get() {
   return this.userRepo.find();
  }
}

UserController

import { Controller, Get } from '@nestjs/common';

import { UserService } from './user.service';

@Controller('/users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  // others method //

  @Get()
  public async getUsers() {
    try {
      const payload = this.userService.get();
      return this.Ok(payload);
    } catch (err) {
      return this.InternalServerError(err);
    }
  }
}

我如何为存储库,服务和控制器创建单元测试,而无需实际持久存储或将数据检索到数据库(使用模拟)?

1 个答案:

答案 0 :(得分:1)

使用Nest公开的测试工具@nestjs/testing可以很容易地在NestJS中进行模拟。简而言之,您将要为要模拟的依赖项创建一个Custom Provider,仅此而已。但是,最好总是看一个示例,因此有可能对控制器进行模拟:

describe('UserController', () => {
  let controller: UserController;
  let service: UserService;
  beforeEach(async () => {
    const moduleRef = await Test.createTestingModule({
      controllers: [UserController],
      providers: [
        {
          provide: UserService,
          useValue: {
            get: jest.fn(() => mockUserEntity) // really it can be anything, but the closer to your actual logic the better
          }
        }
      ]
    }).compile();
    controller = moduleRef.get(UserController);
    service = moduleRef.get(UserService);
  });
});

从那里您可以继续编写测试。这与使用Nest的DI系统进行的所有测试的设置几乎相同,唯一需要注意的是需要使用的@InjectRepository()@InjectModel()(猫鼬和Sequilize装饰器)之类的东西getRepositoryToken()getModelToken()用于注入令牌。如果您正在寻找更多的珍品take a look at this repository