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);
}
}
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();
});
});
});