【问题标题】:How To Mock Repository, Service and Controller In NestJS (Typeorm & Jest)如何在 NestJS 中模拟存储库、服务和控制器(Typeorm & Jest)
【发布时间】:2020-03-13 04:23:28
【问题描述】:

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

用户存储库

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

用户服务

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

用户控制器

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

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

【问题讨论】:

    标签: node.js typescript jestjs nestjs typeorm


    【解决方案1】:

    使用 Nest 公开的测试工具 @nestjs/testing 可以很容易地在 NestJS 中进行 Mocking。简而言之,您需要为要模拟的依赖项创建一个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()(Mongoose 和 Sequilize 装饰器)之类的东西,您需要使用 getRepositoryToken()getModelToken() 用于注入令牌。如果您正在寻找更多示例take a look at this repository

    【讨论】:

    • 您能提供一个完整的例子吗?我希望实现同样的目标。
    • 我的答案中链接的存储库有完整的示例,您可以查看@p0tta
    • 我之前没找对地方。现在找到了,谢谢!
    猜你喜欢
    • 2020-04-19
    • 2020-06-06
    • 2019-08-17
    • 2019-11-20
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 2019-07-05
    相关资源
    最近更新 更多