1

does someone know how to write E2E test for nest microservices? Giving this code?

main.ts

import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.createMicroservice(AppModule, {
    transport: Transport.TCP,
  });
  app.listen(() => console.log('Microservice is listening'));
}
bootstrap();

app.controller.ts

import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';

@Controller()
export class MathController {
  @MessagePattern({ cmd: 'sum' })
  accumulate(data: number[]): number {
    return (data || []).reduce((a, b) => a + b);
  }
}
Georgian Stan
  • 1,865
  • 3
  • 13
  • 27

1 Answers1

6

This should work for you:

import { INestApplication } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { ClientsModule, Transport, ClientProxy } from '@nestjs/microservices';
import * as request from 'supertest';
import { Observable } from 'rxjs';

describe('Math e2e test', () => {
  let app: INestApplication;
  let client: ClientProxy;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [
        MathModule,
        ClientsModule.register([
          { name: 'MathService', transport: Transport.TCP },
        ]),
      ],
    }).compile();

    app = moduleFixture.createNestApplication();

    app.connectMicroservice({
      transport: Transport.TCP,
    });

    await app.startAllMicroservicesAsync();
    await app.init();

    client = app.get('MathService');
    await client.connect();
  });

  afterAll(async () => {
    await app.close();
    client.close();
  });

  it('test accumulate', done => {
    const response: Observable<any> = client.send(
      { cmd: 'sum' },
      { data: [1, 2, 3] },
    );

    response.subscribe(sum=> {
      expect(sum).toBe(6);
      done();
    });
  });
});
Troy Kessler
  • 377
  • 1
  • 8
  • 1
    Yep, thnx this is it. One simple change: const response: Observable = client.send( { cmd: 'sum' }, [1, 2, 3], ); Send only the array not an object – Georgian Stan Jan 31 '20 at 19:02
  • 1
    This is great! Surprised that there was nothing in the docs for this. – Eric Haynes May 21 '21 at 01:33
  • how can i use interceptor for the microservice? i've tried to use useGlobalInterceptor for it but it doesn't work. – KR1470R Aug 10 '23 at 08:11