Spaces:
Runtime error
Runtime error
| import { expect } from 'chai'; | |
| import WebSocket from 'ws'; | |
| import express, { Application, Request, Response } from "express"; | |
| import * as http from "http"; | |
| import { HapticLinkServer } from '../src/socket/hapticLinkServer'; | |
| import { registerRoutes } from '../src/socket/routes'; | |
| import WebSocketWrapper from '../src/socket/WebSocketAdapter'; | |
| describe('WebSocket Server', function() { | |
| const port: number = parseInt(process.env.PORT as string, 10) || 3000; | |
| let wsClient: WebSocket; | |
| let server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse> | |
| before((done) => { | |
| const app: Application = express(); | |
| server = http.createServer(app); | |
| const wss = new WebSocket.Server({ server }); | |
| app.get("/", (_req: Request, res: Response) => { | |
| res.send("Bonjour"); | |
| }); | |
| const hapticLink = new HapticLinkServer(); | |
| registerRoutes(hapticLink); | |
| wss.on("connection", (ws: WebSocket) => { | |
| const wsw = new WebSocketWrapper(ws); | |
| ws.on("message", (message: string) => { | |
| hapticLink.handleRoute(wsw, message); | |
| }); | |
| ws.on("close", () => { | |
| hapticLink.removeUser(wsw); | |
| }); | |
| ws.on("error", () => { | |
| hapticLink.removeUser(wsw); | |
| }); | |
| ws.send("Welcome"); | |
| }); | |
| server.listen(port, () => { | |
| wsClient = new WebSocket('ws://localhost:3000'); | |
| wsClient.on('open', done); | |
| }); | |
| server.on("error", (err) => { | |
| done(err); | |
| }) | |
| }); | |
| after(() => { | |
| // Close the WebSocket client | |
| if (wsClient.readyState === WebSocket.OPEN) { | |
| wsClient.close(); | |
| } | |
| server.close(); | |
| }); | |
| it('should start, listen, and respond to test_connection', (done) => { | |
| // Listen for messages from the server | |
| wsClient.on('message', (data: string) => { | |
| expect(JSON.parse(data).message).to.equal("test_connection_response"); | |
| done(); | |
| }); | |
| // Send a ping message to the server | |
| wsClient.send(JSON.stringify({ "route": "test_connection" })); | |
| }); | |
| }); | |