@@ -5,16 +5,21 @@ import * as express from 'express';
55import { join } from 'path' ;
66import * as request from 'supertest' ;
77import { GrpcController } from '../src/grpc/grpc.controller' ;
8+ import * as ProtoLoader from '@grpc/proto-loader' ;
9+ import * as GRPC from 'grpc' ;
10+ import { expect } from 'chai' ;
11+ import { fail } from 'assert' ;
812
913describe ( 'GRPC transport' , ( ) => {
1014 let server ;
1115 let app : INestApplication ;
16+ let client : any ;
1217
13- beforeEach ( async ( ) => {
18+ before ( async ( ) => {
1419 const module = await Test . createTestingModule ( {
1520 controllers : [ GrpcController ] ,
1621 } ) . compile ( ) ;
17-
22+ // Create gRPC + HTTP server
1823 server = express ( ) ;
1924 app = module . createNestApplication ( server ) ;
2025 app . connectMicroservice ( {
@@ -24,18 +29,57 @@ describe('GRPC transport', () => {
2429 protoPath : join ( __dirname , '../src/grpc/math.proto' ) ,
2530 } ,
2631 } ) ;
32+ // Start gRPC microservice
2733 await app . startAllMicroservicesAsync ( ) ;
2834 await app . init ( ) ;
35+ // Load proto-buffers for test gRPC dispatch
36+ const proto = ProtoLoader
37+ . loadSync ( join ( __dirname , '../src/grpc/math.proto' ) ) as any ;
38+ // Create Raw gRPC client object
39+ const protoGRPC = GRPC . loadPackageDefinition ( proto ) as any ;
40+ // Create client connected to started services at standard 5000 port
41+ client = new protoGRPC . math . Math (
42+ 'localhost:5000' ,
43+ GRPC . credentials . createInsecure ( ) ,
44+ ) ;
45+
2946 } ) ;
3047
31- it ( `/ POST` , ( ) => {
48+ it ( `GRPC Sending and Receiving HTTP POST` , ( ) => {
3249 return request ( server )
3350 . post ( '/' )
3451 . send ( [ 1 , 2 , 3 , 4 , 5 ] )
3552 . expect ( 200 , { result : 15 } ) ;
3653 } ) ;
3754
38- afterEach ( async ( ) => {
55+ it ( 'GRPC Sending and receiving Stream' , async ( ) => {
56+
57+ const callHandler = client . SumStream ( ) ;
58+
59+ callHandler . on ( 'data' , ( msg : number ) => {
60+ // Do deep comparison (to.eql)
61+ expect ( msg ) . to . eql ( { result : 15 } ) ;
62+ callHandler . cancel ( ) ;
63+ } ) ;
64+
65+ callHandler . on ( 'error' , ( err : any ) => {
66+ // We want to fail only on real errors while Cancellation error
67+ // is expected
68+ if ( String ( err ) . toLowerCase ( ) . indexOf ( 'cancelled' ) === - 1 ) {
69+ fail ( 'gRPC Stream error happened, error: ' + err ) ;
70+ }
71+ } ) ;
72+
73+ return new Promise ( ( resolve , reject ) => {
74+ callHandler . write ( { data : [ 1 , 2 , 3 , 4 , 5 ] } ) ;
75+ setTimeout ( ( ) => resolve ( ) , 1000 ) ;
76+ } ) ;
77+
78+ } ) ;
79+
80+ after ( async ( ) => {
3981 await app . close ( ) ;
82+ client . close ;
4083 } ) ;
84+
4185} ) ;
0 commit comments