From 9d6373276333f6cdf633f8d6c85273616191fecb Mon Sep 17 00:00:00 2001 From: Tolga Paksoy Date: Thu, 20 Oct 2022 16:55:01 +0200 Subject: [PATCH] test(fastify): add specs for sse --- .../nest-application/sse/e2e/fastify.spec.ts | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 integration/nest-application/sse/e2e/fastify.spec.ts diff --git a/integration/nest-application/sse/e2e/fastify.spec.ts b/integration/nest-application/sse/e2e/fastify.spec.ts new file mode 100644 index 00000000000..4fc1ebf2029 --- /dev/null +++ b/integration/nest-application/sse/e2e/fastify.spec.ts @@ -0,0 +1,86 @@ +import { + FastifyAdapter, + NestFastifyApplication, +} from '@nestjs/platform-fastify'; +import { Test } from '@nestjs/testing'; +import { expect } from 'chai'; +import * as EventSource from 'eventsource'; +import { AppModule } from '../src/app.module'; + +describe('Sse (Fastify Application)', () => { + let app: NestFastifyApplication; + let eventSource: EventSource; + + describe('without forceCloseConnections', () => { + beforeEach(async () => { + const moduleFixture = await Test.createTestingModule({ + imports: [AppModule], + }).compile(); + + app = moduleFixture.createNestApplication( + new FastifyAdapter(), + ); + + await app.listen(3000); + const url = await app.getUrl(); + + eventSource = new EventSource(url + '/sse', { + headers: { connection: 'keep-alive' }, + }); + }); + + // The order of actions is very important here. When not using `forceCloseConnections`, + // the SSe eventsource should close the connections in order to signal the server that + // the keep-alive connection can be ended. + afterEach(async () => { + eventSource.close(); + + await app.close(); + }); + + it('receives events from server', done => { + eventSource.addEventListener('message', event => { + expect(JSON.parse(event.data)).to.eql({ + hello: 'world', + }); + done(); + }); + }); + }); + + describe('with forceCloseConnections', () => { + beforeEach(async () => { + const moduleFixture = await Test.createTestingModule({ + imports: [AppModule], + }).compile(); + + app = moduleFixture.createNestApplication( + new FastifyAdapter({ + forceCloseConnections: true, + }), + ); + + await app.listen(3000); + const url = await app.getUrl(); + + eventSource = new EventSource(url + '/sse', { + headers: { connection: 'keep-alive' }, + }); + }); + + afterEach(async () => { + await app.close(); + + eventSource.close(); + }); + + it('receives events from server', done => { + eventSource.addEventListener('message', event => { + expect(JSON.parse(event.data)).to.eql({ + hello: 'world', + }); + done(); + }); + }); + }); +});