无法模拟 createQueryBuilder 函数 typeorm nestjs jest

时间:2021-02-15 08:52:34

标签: jestjs nestjs typeorm ts-jest

我正在尝试为我的服务文件编写单元测试用例。有一个函数 linkDevice 连接 2 个表 user 和 device 并返回对象。我检查设备是否已分配给用户。如果分配了它,我会抛出一个 BadRequestExcpetion,如果没有,我将它添加到用户。

我尝试向 where 函数添加一个 mockResolvedValue,但出现以下错误

 TypeError: Cannot read property 'mockResolvedValue' of undefined

      129 |       new BadRequestException(),
      130 |     );
    > 131 |     profileRepository.createQueryBuilder.where.mockResolvedValue();
          |                                                ^
      132 |     const result = await service.linkDevice(device, 2);
      133 |     console.log(result);
      134 |     expect(service.linkDevice).toHaveBeenCalledWith(device, 2);

service.spec.ts

 beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ProfileService,
        {
          provide: getRepositoryToken(Profile),
          useValue: {
            create: jest.fn(),
            save: jest.fn(),
            findOne: jest.fn(),
            createQueryBuilder: jest.fn(() => ({
              where: jest.fn().mockReturnThis(),
              setParameter: jest.fn().mockReturnThis(),
              leftJoinAndSelect: jest.fn().mockReturnThis(),
              getOne: jest.fn().mockReturnThis(),
            })),
          },
        },
      ],
    }).compile();

    service = module.get<ProfileService>(ProfileService);
    profileRepository = module.get(getRepositoryToken(Profile));
  });

 it('should throw error if device is already linked to profile', async () => {
    profileRepository.createQueryBuilder.mockResolvedValue(
      new BadRequestException(),
    );
    const result = await service.linkDevice(device, 2);
    console.log(result);
    expect(service.linkDevice).toHaveBeenCalledWith(device, 2);
  });

错误

  TypeError: this.profileRepository.createQueryBuilder(...).where is not a function

      55 |     const user = await this.profileRepository
      56 |       .createQueryBuilder('profile')
    > 57 |       .where('profile.id = :id')
         |        ^
      58 |       .setParameter('id', userId)
      59 |       .leftJoinAndSelect('profile.device', 'device')
      60 |       .getOne();

      at ProfileService.linkDevice (../src/modules/profile/profile.service.ts:57:8)
      at Object.<anonymous> (profile.service.spec.ts:131:34)

1 个答案:

答案 0 :(得分:1)

如果您想抛出错误,您应该使用 mockRejectedValue 而不是 mockResolvedValue。您可能还想专门使用 mockRejectedValueOnce,否则您将覆盖之前设置的模拟。否则你的模拟设置看起来不错。