如何在服务nestjs中模拟getMongoRepository

时间:2019-07-23 02:28:19

标签: node.js mongodb typescript nestjs typeorm

我在nestjs中为我的服务编写单元测试。在我的函数删除中,我使用getMongoRepository进行删除。但是我坚持写单元测试

我已经尝试过编写模拟游戏,但是没有用

我的服务

 async delete(systemId: string): Promise<DeleteWriteOpResultObject> {
    const systemRepository = getMongoRepository(Systems);
    return await systemRepository.deleteOne({ systemId });
  }

我的模拟

import { Mock } from './mock.type';
import { Repository, getMongoRepository } from 'typeorm';

// @ts-ignore
export const mockRepositoryFactory: () => Mock<Repository<any>> = jest.fn(
  () => ({
    save: jest.fn(Systems => Systems),
    delete: jest.fn(Systems => Systems),
    deleteOne: jest.fn(Systems => Systems),
  }),
);

我的测试

import { ExternalSystemService } from '../external-system.service';
import { Systems } from '../entities/external-system.entity';

module = await Test.createTestingModule({
      providers: [
        ExternalSystemService,
        {
          provide: getRepositoryToken(Systems),
          useFactory: mockRepositoryFactory,
        },
      ],
    }).compile();

    service = module.get<ExternalSystemService>(ExternalSystemService);
    mockRepository = module.get(getRepositoryToken(Systems));

 describe('delete', () => {
    it('should delete the system', async () => {
      mockRepository.delete.mockReturnValue(undefined);
      const deletedSystem = await service.delete(systemOne.systemId);

      expect(mockRepository.delete).toBeCalledWith({ systemId: systemOne.systemId });
      expect(deletedSystem).toBe(Object);
    });

我收到此错误

ExternalSystemService›删除›不应删除系统

ConnectionNotFoundError: Connection "default" was not found.

  at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)
  at ConnectionManager.Object.<anonymous>.ConnectionManager.get (connection/ConnectionManager.ts:40:19)
  at Object.getMongoRepository (index.ts:300:35)
  at Object.<anonymous> (external-system/tests/external-system.service.spec.ts:176:33)
  at external-system/tests/external-system.service.spec.ts:7:71
  at Object.<anonymous>.__awaiter (external-system/tests/external-system.service.spec.ts:3:12)
  at Object.<anonymous> (external-system/tests/external-system.service.spec.ts:175:51)

1 个答案:

答案 0 :(得分:0)

您应该避免使用全局函数,而应使用dependency injection系统;这使测试变得更加容易,并且是nest的主要功能之一。

嵌套typeorm module已经提供了injecting a repository的便捷方式:

1)将存储库注入服务的构造函数中:

constructor(
  @InjectRepository(Systems)
  private readonly systemsRepository: MongoRepository<Systems>,
) {}

2)使用注入的存储库

async delete(systemId: string): Promise<DeleteWriteOpResultObject> {
  return this.systemsRepository.deleteOne({ systemId });
}

现在,您的mocked repository将用于测试。