【发布时间】:2019-12-01 00:16:05
【问题描述】:
我在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)
【问题讨论】:
标签: node.js mongodb typescript nestjs typeorm