【问题标题】:Testing TypeORM repo find function with where option使用 where 选项测试 TypeORM repo 查找功能
【发布时间】:2019-06-23 17:13:50
【问题描述】:

如果未找到结果,我正在尝试测试捕获错误,对实体使用 TypeORM find 函数,并带有 where 的附加选项

我试图模拟该函数,但我似乎无法模拟该函数的 where 位。

服务文件

try {
    historicalTypes = await this.historicalMappingDataTypesRepo.find({
     where: {
          HistoricalTypes: 'Contracts',
        },
    });
}
catch (e) {
  if (e instanceof Error) {
    this.logger.error(`Historical mapping type contracts could not found: ${e.message}`, e.stack);
  } else {
    this.logger.error(`Historical mapping type contracts could not found: ${e}`);
  }
  return;
}

测试

const mockHistoricalTypes: HistoricalTypes[] = [
    {
      HistoricalTypeID: 1,
      HistoricalType: 'Contracts',
    },
];

const mockHistoricalMappingTypesRepo = {
    find: ({where}) => Promise.resolve(mockHistoricalMappingTypes),
};

beforeAll(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        HistoricalMappingSchedulerService,
        {
          provide: HistoricalMappingSchedulerRepository,
          useValue: mockHistoricalMappingSchedulerRepository,
        },
        {
          provide: getRepositoryToken(HistoricalMappingTypes),
          useValue: mockHistoricalMappingTypesRepo,
        },
      ],
    }).compile();
    service = module.get<HistoricalMappingSchedulerService>(HistoricalMappingSchedulerService);
});

it('should throw an error when historical type id is not found', async () => {
    await mockHistoricalMappingTypesRepo.find({
      where: {
        HistoricalMappingType: 'Testing',
      },
    });
    const mockFn = () => service.ContractHistoricalMapping();
    expect(mockFn).toThrowError();
});

【问题讨论】:

  • 还有问题吗? :-)

标签: javascript node.js typescript nestjs typeorm


【解决方案1】:

我建议使用jest.fn() 模拟存储库:

mockHistoricalMappingTypesRepo = new (jest.fn(() => ({
  find: jest.fn(),
})))();

在您的测试中,您可以使用mockImplementation 控制存储库返回的内容:

mockHistoricalMappingTypesRepo.find.mockImplementation(() => throw new Error());
try {
  await service.ContractHistoricalMapping()
  fail('Should have thrown error!');
} catch (e) {
  expect(e).toBeInstanceOf(Error);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 1970-01-01
    相关资源
    最近更新 更多