How to test GRPC with Nest and Jest?

Viewed 1808

I am trying to test a GRPC method but I am getting this error when running in Jest: TypeError: Cannot read property 'gprcFindAll' of undefined

This is the documentation I am referencing: https://docs.nestjs.com/microservices/grpc

Here is my controller:

@Controller('benchmarks')
export class BenchmarksController {

    @GrpcMethod('HelloWorldGRPCService', 'findAll')
    async gprcFindAll(metadata?: any): Promise<Benchmarks[]> {
        const benchmarks = [];
        return benchmarks;
    }
}

Here is my Jest test:

describe('Benchmarks Controller', () => {
    let controller: BenchmarksController;

    beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
            controllers: [BenchmarksController]
        }).compile();

        controller = module.get<BenchmarksController>(BenchmarksController);
    });

    it('should be defined', () => {
        expect(controller).toBeDefined();
    });

    it('GRPC Should Find All', async function() {
        const result = await controller.gprcFindAll();
        console.log(result);
    }); 
});

Here is my Proto 3 file:

syntax = "proto3";

package helloWorldGRPC;

service HelloWorldGRPCService {
    rpc findAll () returns (repeated Benchmarks);
}

message Benchmarks {
    string trans_id = 1;
    string protocol = 2;
    string database = 3;
    Timestamp updated_at = 4;
    Timestamp created_at = 5;
    repeated Action actions = 6;
}

message Action {
    string trans_id = 1;
    int32 payload_length = 2;
    string payload = 3;
    string status = 4;
    Timestamp updated_at = 5;
    Timestamp created_at = 6;
}
1 Answers

I know this is old but i figured i'd answer encase someone from google comes across this issue.

Both @GrpcMethod() decorator arguments are optional. If called without the second argument (e.g., 'FindOne'), Nest will automatically associate the .proto file rpc method with the handler based on converting the handler name to upper camel case (e.g., the findOne handler is associated with the FindOne rpc call definition). This is shown below.

it is saying it is undefined because it is undefined. it is looking for gprcFindAll however you have named the method findAll as the second param.

either omit findAll

@GrpcMethod('HelloWorldGRPCService')
async gprcFindAll(metadata?: any): Promise<Benchmarks[]> {
    const benchmarks = [];
    return benchmarks;
}

or change the second param to match the handler

@GrpcMethod('HelloWorldGRPCService', 'GprcFindAll')
async gprcFindAll(metadata?: any): Promise<Benchmarks[]> {
    const benchmarks = [];
    return benchmarks;
}
Related