Skip to content

Commit

Permalink
273rd Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Shyam-Chen committed Feb 26, 2024
1 parent a593249 commit 1e266cc
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
7 changes: 3 additions & 4 deletions src/routes/echo/+handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,15 @@ import type { FastifyInstance } from 'fastify';

export default async (app: FastifyInstance) => {
app.get('', { websocket: true }, (con) => {
console.log('Client connected');

con.socket.send(`Hello from Fastify!`);
app.log.info('Client connected');

con.socket.on('message', (message: MessageEvent) => {
console.log(`Client message: ${message}`);
con.socket.send(`Hello from Fastify!`);
});

con.socket.on('close', () => {
console.log('Client disconnected');
app.log.info('Client disconnected');
});
});
};
28 changes: 28 additions & 0 deletions src/routes/echo/__tests__/+handler.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { test, expect } from 'vitest';
import fastify from 'fastify';
import websocket from '@fastify/websocket';

import echo from '../+handler';

test('WS /echo', async () => {
const app = fastify();

app.register(websocket);
app.register(echo, { prefix: '/echo' });

await app.ready();
const ws = await app.injectWS('/echo');

let resolve: (value: string) => void;
const promise = new Promise<string>((_resolve) => (resolve = _resolve));

ws.on('message', (data: MessageEvent) => {
resolve(data.toString());
});

ws.send('Hi from Test!');

expect(await promise).toEqual('Hello from Fastify!');

ws.terminate();
});

0 comments on commit 1e266cc

Please sign in to comment.