带有模拟存储库的 Nestjs 服务测试不起作用

Posted

技术标签:

【中文标题】带有模拟存储库的 Nestjs 服务测试不起作用【英文标题】:Nestjs service test with mock repository not working 【发布时间】:2021-09-14 18:14:53 【问题描述】:

我正在使用 Typeorm 在 Nestjs 中测试员工服务。该服务有一个注入的员工存储库。我的测试策略是模拟一个简单的存储库来测试服务。

import  Test, TestingModule  from '@nestjs/testing';
import  getRepositoryToken  from '@nestjs/typeorm';
import  getRepository, Repository  from 'typeorm';
import  CreateEmployeeDto  from './dto/create-employee.dto';
import  Employee  from './employee.entity';
import  EmployeesService  from './employees.service';
describe('EmployeesService', () => 
  let service: EmployeesService;

  const mockEmployeesRepository = 
    save: jest.fn().mockImplementation((dto: CreateEmployeeDto) => 
      return Promise.resolve(
        EmployeeID: Math.ceil(Math.random() * 10),
        ...dto,
      );
    ),
  ;

  beforeEach(async () => 
    const module: TestingModule = await Test.createTestingModule(
      providers: [
        EmployeesService,
        
          provide: getRepositoryToken(Employee),
          useValue: mockEmployeesRepository,
        ,
      ],
    ).compile();

    service = module.get<EmployeesService>(EmployeesService);
  );

  it('should be defined', () => 
    expect(service).toBeDefined();
  );

但我收到了EmployeesService › should be defined 错误。即使在检查Inject TypeORM repository into NestJS service for mock data testing 之后,我也无法弄清楚为什么EmployeesService 在这个简单的测试中不起作用。

更多错误信息:

EmployeesService › should be defined

    expect(received).toBeDefined()

    Received: undefined

      35 |
      36 |   it('should be defined', () =>   
    > 37 |     expect(service).toBeDefined(); 
         |                     ^

employees.service.ts

@Injectable()
export class EmployeesService 
  constructor(
    @InjectRepository(Employee, 'db1')
    private employeesRepository: Repository<Employee>,
  ) 

  findById(id: number): Promise<Employee> 
    return this.employeesRepository.findOneOrFail(id);
  

  async createEmployee(createEmployeeDto: CreateEmployeeDto) 
    const newEmployee = createEmployeeDto;
    try 
      await this.employeesRepository.save(newEmployee);
     catch (error) 
      throw new BadRequestException('Cannot create employee');
    

    return newEmployee;
  

  async deleteEmployee(id: number) 
    try 
      return await this.employeesRepository.delete(id);
     catch (error) 
      throw new BadRequestException('Cannot delete employee');
    
  

  async updateEmployee(id: number, body: UpdateEmployeeDto) 
    const employee = this.employeesRepository.findOne(id);
    if (!employee) 
      throw new NotFoundException('Employee not found');
    

    const updatedEmployee = await this.employeesRepository.update(id, body);

    return this.employeesRepository.findOne(id);
  

【问题讨论】:

这个测试套件非常标准。你能告诉我们EmployeesService吗? 您还可以添加遇到的任何错误吗? 添加错误信息和employee.service代码。谢谢 【参考方案1】:

这是您的 EmployeeService 构造函数:

constructor(
    @InjectRepository(Employee, 'db1')
    private employeesRepository: Repository<Employee>,
  ) 

您正在注入两件事​​,但您并没有同时通过。你只通过了一个:

const module: TestingModule = await Test.createTestingModule(
      providers: [
        EmployeesService,
        
          provide: getRepositoryToken(Employee),
          useValue: mockEmployeesRepository,
        ,
      ],
    ).compile();

这个模块是一个独立的 DI 容器。您必须列出注入服务的内容

【讨论】:

以上是关于带有模拟存储库的 Nestjs 服务测试不起作用的主要内容,如果未能解决你的问题,请参考以下文章

如何在服务nestjs中模拟getMongoRepository

NestJS TypeORM mongodb 在数组列中查找不起作用

当类型是 Record <k,v> - NestJS 时,类验证器不起作用

如何开玩笑模拟nestjs导入?

JwtModule.registerAsync 在 NestJS 中不起作用

Nest JS / MongoDB - 地理空间索引在部署的服务器上不起作用