Home > Net >  Mock grpc service in unit testing nestjs
Mock grpc service in unit testing nestjs

Time:05-17

I want write an unit test for my getAllGroups() method in mail.service.ts:

public async getAllGroup(): Promise<{ id: number, name: string }[]> {
  try {
    return (await lastValueFrom(this.groupService.GetAllGroup({}))).groups;
  } catch (error) {
    throw error;
  }
}

The problem is i want to mock GetAllGroups() that is a grpc method and fetch datas. how i add groupService in mail.service.ts:

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

In mail.service.spec.ts how i provide groupService:

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

And the test i write for getAllGroups() method:

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" }
    ]);
})

After test execution its failed and return this:

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 |     })

CodePudding user response:

I found the problem ... I should use await before service.getAllGroup() Like this:

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