在单元测试 nestjs 中模拟 grpc 服务

Mock grpc service in unit testing nestjs

我想为 mail.service.ts:

中的 getAllGroups() 方法编写单元测试
public async getAllGroup(): Promise<{ id: number, name: string }[]> {
  try {
    return (await lastValueFrom(this.groupService.GetAllGroup({}))).groups;
  } catch (error) {
    throw error;
  }
}

问题是我想模拟 GetAllGroups() 这是一个 grpc 方法并获取数据。 我如何在 mail.service.ts:

中添加 groupService
constructor(
  @Inject('groupService') private groupClient: ClientGrpc,
) { }
private readonly groupService = this.groupClient.getService<GroupService>('groupService');

mail.service.spec.ts中我是如何提供groupService的:

{
   provide: 'groupService',
   useValue: createMock<ClientGrpc>()
             .getService<GroupService>('groupService')
}

我为 getAllGroups() 方法编写的测试:

it(`getAllGroup() should return list of gropus`, async () => {
    const groupMock = createMock<MailService>();
    groupMock.GetAllGroup.mockReturnValue( of({ groups: [{ id: 123, name: "abc" }] }));

    expect(service.getAllGroup()).toEqual([
        { id: 123, name: "abc" }
    ]);
})

测试执行失败后 return 这个:

Expected: [{"id": 123, "name": "abc"}]
Received: {}

  56 |         groupMock.GetAllGroup.mockReturnValue( of({ groups: [{ id: 123, name: "abc" }] }));
  57 |
> 58 |         expect(service.getAllGroup()).toEqual([
     |                                       ^
  59 |             { id: 123, name: "abc" }
  60 |         ]);
  61 |     })

我发现了问题... 我应该在 service.getAllGroup() 之前使用 await 像这样:

expect(await service.getAllGroup()).toEqual([
    { id: 123, name: "abc" }
]);