@improbable-eng/grpc-web-fake-transport
Fake Transport for use with @improbable-eng/grpc-web.
Usage
FakeTransportBuilder
builds a Transport
that can be configured to send preset headers, messages, and trailers for testing.
By default the Transport
that FakeTranportBuilder.build()
generates will trigger all of the specified response behaviours (.withHeaders(metadata)
, .withMessages([msgOne, msgTwo])
, .withTrailers(metadata)
) when the client has finished sending.
This is usually the desired flow as all of the response behaviour is triggered only after the client has finished sending as would most commonly occur in production usage.
However, in the case of bi-directional or other complex usage it can be helpful to use .withManualTrigger()
to disable automatic sending of messages or headers/trailers and trigger the sending manually using sendHeaders()
, sendMessages()
and sendTrailers()
.
With Service Stubs generated by ts-protoc-gen
import { FakeTransportBuilder } from '@improbable-eng/grpc-web-fake-transport';
const fakeTransport = new FakeTransportBuilder()
.withMessages([ new PingResponse() ])
.build();
const client = new PingServiceClient("https://example.com", {
transport: fakeTransport
});
client.DoPing();
With grpc-web
import { grpc } from '@improbable-eng/grpc-web';
import { FakeTransportBuilder } from '@improbable-eng/grpc-web-fake-transport';
const fakeTransport = new FakeTransportBuilder()
.withMessages([ new PingResponse() ])
.build();
grpc.invoke(PingService.DoPing, {
host: "https://example.com",
transport: fakeTransport,
});
With withManualTrigger()
import { grpc } from '@improbable-eng/grpc-web';
import { FakeTransportBuilder } from '@improbable-eng/grpc-web-fake-transport';
const fakeTransport = new FakeTransportBuilder()
.withManualTrigger()
.withHeaders(new grpc.Metadata({ headerKey: "value" }))
.withMessages([ new PingResponse() ])
.withTrailers(new grpc.Metadata({ trailerKey: "value" }))
.build();
grpc.invoke(PingService.DoPing, {
host: "https://example.com",
transport: fakeTransport,
});
fakeTransport.sendHeaders();
fakeTransport.sendMessages();
fakeTransport.sendTrailers();
Alternatively replace the Default Transport when initialising your tests:
import { grpc } from "@improbable-eng/grpc-web";
import { NodeHttpTransport } from "@improbable-eng/grpc-web-fake-transport";
grpc.setDefaultTransport(fakeTransport);