Nest JS微服务TCP E2E测试

问题描述 投票:0回答:1

有人知道如何为嵌套微服务编写E2E测试吗?提供此代码?

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);
  }
}
microservices e2e-testing nestjs
1个回答
0
投票

这应该为您工作:

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();
    });
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.