简体   繁体   English

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

[英]How To Mock Repository, Service and Controller In NestJS (Typeorm & Jest)

I'm new at typescript.我是打字稿的新手。 My Nestjs project app is something like this.我的 Nestjs 项目应用程序是这样的。 I'm trying to use repository pattern, so i separated business logic (service) and persistance logic (repository)我正在尝试使用存储库模式,所以我分离了业务逻辑(服务)和持久化逻辑(存储库)

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);
    }
  }
}

How do i create unit testing for repository, service & controller without actually persist or retrieve data to DB (using mock)?我如何为存储库、服务和控制器创建单元测试而不实际将数据持久化或检索到数据库(使用模拟)?

Mocking in NestJS is pretty easily obtainable using the testing tools Nest exposes is @nestjs/testing .使用 Nest 公开的测试工具@nestjs/testing可以很容易地获得@nestjs/testing In short, you'll want to create a Custom Provider for the dependency you are looking to mock, and that's all there is.简而言之,您需要为要模拟的依赖项创建一个自定义提供程序,这就是全部。 However, it's always better to see an example, so here is a possibility of a mock for the controller:然而,看一个例子总是更好,所以这里有一个控制器模拟的可能性:

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);
  });
});

And from there you can go on and write your tests.从那里你可以继续编写你的测试。 This is pretty much the same set up for all tests using Nest's DI system, the only thing to be aware of is things like @InjectRepository() and @InjectModel() (Mongoose and Sequilize decorators) where you'll need to use getRepositoryToken() or getModelToken() for the injection token.这与使用 Nest 的 DI 系统的所有测试的设置几乎相同,唯一需要注意的是诸如@InjectRepository()@InjectModel() (Mongoose 和 Sequilize 装饰器)之类的东西,您需要使用getRepositoryToken()getModelToken()用于注入令牌。 If you're looking for more exmaples take a look at this repository如果您正在寻找更多示例,请查看此存储库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM