gRPC with TypeScript: Testing ts-proto Generated Services and Clients

gRPC with TypeScript: Testing ts-proto Generated Services and Clients

TypeScript gRPC testing is less documented than Go or Python — most examples use JavaScript or reference outdated grpc packages. This guide uses the modern stack: @grpc/grpc-js as the gRPC library, ts-proto for type-safe generated code, and Jest for testing.

The TypeScript gRPC Stack

Modern TypeScript gRPC uses:

  • @grpc/grpc-js — the official gRPC library (replaces deprecated grpc package)
  • ts-proto — generates idiomatic TypeScript types (not the old google-protobuf JS classes)
  • buf — manages code generation
  • Jest — test runner

Install:

npm install @grpc/grpc-js @grpc/proto-loader
npm install --save-dev ts-proto jest @types/jest ts-jest

Generating TypeScript Code with ts-proto

# buf.gen.yaml
version: v2

plugins:
  - remote: buf.build/community/stephenh-ts-proto
    out: src/gen
    opt:
      - outputServices=grpc-js  # Generate grpc-js compatible service definitions
      - esModuleInterop=true
      - useOptionals=messages
      - stringEnums=true

This generates:

// src/gen/user/v1/user.ts (auto-generated)
export interface User {
  id: string;
  email: string;
  displayName: string;
  createdAt: bigint;
}

export interface GetUserRequest {
  userId: string;
}

export interface GetUserResponse {
  user?: User;
}

export const UserServiceDefinition = {
  GetUser: {
    path: "/user.v1.UserService/GetUser",
    requestStream: false,
    responseStream: false,
    requestSerialize: (request: GetUserRequest) => ...,
    responseDeserialize: (buffer: Buffer) => ...,
  },
  // ...
};

Implementing a gRPC Service

// src/user-service.ts
import * as grpc from "@grpc/grpc-js";
import { UserServiceDefinition, GetUserRequest, GetUserResponse, User } from "./gen/user/v1/user";

const users: Record<string, User> = {
  "user-1": { id: "user-1", email: "alice@example.com", displayName: "Alice", createdAt: BigInt(1704067200) },
  "user-2": { id: "user-2", email: "bob@example.com", displayName: "Bob", createdAt: BigInt(1704067300) },
};

export const userServiceImpl: grpc.UntypedServiceImplementation = {
  async GetUser(
    call: grpc.ServerUnaryCall<GetUserRequest, GetUserResponse>,
    callback: grpc.sendUnaryData<GetUserResponse>
  ): Promise<void> {
    const { userId } = call.request;
    const user = users[userId];
    
    if (!user) {
      return callback({
        code: grpc.status.NOT_FOUND,
        message: `User ${userId} not found`,
      });
    }
    
    callback(null, { user });
  },
};

Unit Testing the Service Implementation

Test the service handler directly — no gRPC server needed:

// tests/user-service.test.ts
import * as grpc from "@grpc/grpc-js";
import { userServiceImpl } from "../src/user-service";
import { GetUserRequest } from "../src/gen/user/v1/user";

function makeCall(request: GetUserRequest): grpc.ServerUnaryCall<GetUserRequest, any> {
  return {
    request,
    metadata: new grpc.Metadata(),
    cancelled: false,
    // ... minimal mock
  } as any;
}

describe("UserService.GetUser", () => {
  test("returns user when found", (done) => {
    const call = makeCall({ userId: "user-1" });
    
    userServiceImpl.GetUser(call, (error, response) => {
      expect(error).toBeNull();
      expect(response?.user?.id).toBe("user-1");
      expect(response?.user?.email).toBe("alice@example.com");
      done();
    });
  });
  
  test("returns NOT_FOUND for unknown user", (done) => {
    const call = makeCall({ userId: "unknown" });
    
    userServiceImpl.GetUser(call, (error, response) => {
      expect(error).not.toBeNull();
      expect(error?.code).toBe(grpc.status.NOT_FOUND);
      expect(error?.message).toContain("unknown");
      expect(response).toBeUndefined();
      done();
    });
  });
  
  test("returns NOT_FOUND for empty userId", (done) => {
    const call = makeCall({ userId: "" });
    
    userServiceImpl.GetUser(call, (error, _) => {
      expect(error?.code).toBe(grpc.status.NOT_FOUND);
      done();
    });
  });
});

Testing gRPC Clients with Mocks

For code that calls gRPC services (clients), mock the generated client:

// src/user-repository.ts
import { UserServiceClient } from "./gen/user/v1/user";

export class UserRepository {
  constructor(private client: UserServiceClient) {}
  
  async findById(userId: string): Promise<{ id: string; email: string } | null> {
    return new Promise((resolve, reject) => {
      this.client.getUser({ userId }, (error, response) => {
        if (error) {
          if (error.code === 5) {  // NOT_FOUND
            resolve(null);
          } else {
            reject(error);
          }
          return;
        }
        resolve(response?.user ?? null);
      });
    });
  }
}
// tests/user-repository.test.ts
import * as grpc from "@grpc/grpc-js";
import { UserRepository } from "../src/user-repository";

function makeClientMock(getUser: jest.Mock) {
  return { getUser } as any;
}

describe("UserRepository", () => {
  test("findById returns user when found", async () => {
    const mockUser = { id: "user-1", email: "alice@example.com", displayName: "Alice", createdAt: BigInt(0) };
    
    const getUser = jest.fn().mockImplementation((req, callback) => {
      callback(null, { user: mockUser });
    });
    
    const repo = new UserRepository(makeClientMock(getUser));
    const result = await repo.findById("user-1");
    
    expect(result?.id).toBe("user-1");
    expect(result?.email).toBe("alice@example.com");
    expect(getUser).toHaveBeenCalledWith({ userId: "user-1" }, expect.any(Function));
  });
  
  test("findById returns null when not found", async () => {
    const getUser = jest.fn().mockImplementation((req, callback) => {
      callback({ code: grpc.status.NOT_FOUND, message: "not found" });
    });
    
    const repo = new UserRepository(makeClientMock(getUser));
    const result = await repo.findById("unknown");
    
    expect(result).toBeNull();
  });
  
  test("findById throws on unexpected error", async () => {
    const getUser = jest.fn().mockImplementation((req, callback) => {
      callback({ code: grpc.status.INTERNAL, message: "internal error" });
    });
    
    const repo = new UserRepository(makeClientMock(getUser));
    
    await expect(repo.findById("user-1")).rejects.toMatchObject({
      code: grpc.status.INTERNAL,
    });
  });
});

Integration Testing with a Real gRPC Server

For end-to-end tests, spin up a server and connect a real client:

// tests/integration/user-service.integration.test.ts
import * as grpc from "@grpc/grpc-js";
import { createServer } from "../../src/server";
import { UserServiceClient } from "../../src/gen/user/v1/user";
import { promisify } from "util";

describe("UserService Integration", () => {
  let server: grpc.Server;
  let client: UserServiceClient;
  let serverAddress: string;
  
  beforeAll(async () => {
    server = await createServer();
    
    await new Promise<void>((resolve, reject) => {
      server.bindAsync("localhost:0", grpc.ServerCredentials.createInsecure(), (error, port) => {
        if (error) return reject(error);
        server.start();
        serverAddress = `localhost:${port}`;
        resolve();
      });
    });
    
    client = new UserServiceClient(
      serverAddress,
      grpc.credentials.createInsecure()
    );
  });
  
  afterAll(async () => {
    client.close();
    await new Promise<void>((resolve) => server.tryShutdown(resolve));
  });
  
  test("GetUser returns correct user", async () => {
    const getUser = promisify(client.getUser.bind(client));
    const response = await getUser({ userId: "user-1" });
    
    expect(response.user?.id).toBe("user-1");
    expect(response.user?.email).toBe("alice@example.com");
  });
  
  test("GetUser returns NOT_FOUND for missing user", async () => {
    const getUser = promisify(client.getUser.bind(client));
    
    await expect(getUser({ userId: "nonexistent" })).rejects.toMatchObject({
      code: grpc.status.NOT_FOUND,
    });
  });
});

Testing Protobuf Serialization

ts-proto generates encode/decode functions for every message. Test them directly:

// tests/proto-serialization.test.ts
import { User, GetUserRequest, GetUserResponse } from "../src/gen/user/v1/user";

test("User message encodes and decodes correctly", () => {
  const original: User = {
    id: "user-123",
    email: "alice@example.com",
    displayName: "Alice Wonderland",
    createdAt: BigInt(1704067200),
  };
  
  const encoded = User.encode(original).finish();
  const decoded = User.decode(encoded);
  
  expect(decoded.id).toBe(original.id);
  expect(decoded.email).toBe(original.email);
  expect(decoded.displayName).toBe(original.displayName);
  expect(decoded.createdAt).toBe(original.createdAt);
});

test("Empty optional fields serialize to defaults", () => {
  const request: GetUserRequest = { userId: "" };
  
  const encoded = GetUserRequest.encode(request).finish();
  const decoded = GetUserRequest.decode(encoded);
  
  expect(decoded.userId).toBe("");  // Not undefined
});

Jest Configuration

// jest.config.ts
export default {
  preset: "ts-jest",
  testEnvironment: "node",
  roots: ["<rootDir>/tests"],
  testMatch: ["**/*.test.ts"],
  testPathIgnorePatterns: ["integration"],  // Separate integration tests
  collectCoverageFrom: ["src/**/*.ts", "!src/gen/**"],  // Exclude generated code
};
// jest.config.integration.ts
export default {
  preset: "ts-jest",
  testEnvironment: "node",
  testMatch: ["**/integration/**/*.test.ts"],
  testTimeout: 30000,  // 30s for network tests
};

CI Configuration

# .github/workflows/grpc-ts-tests.yml
- name: Unit tests
  run: npx jest --coverage

- name: Integration tests
  run: npx jest --config jest.config.integration.ts

Conclusion

TypeScript gRPC testing with @grpc/grpc-js and ts-proto follows the same pattern as any TypeScript service: unit test handlers directly, mock clients for business logic tests, and add integration tests for end-to-end validation. The type safety from ts-proto means many proto schema bugs become TypeScript compiler errors before they become test failures — which is exactly the right place to catch them.

Read more

Start now free