fastify-websocket icon indicating copy to clipboard operation
fastify-websocket copied to clipboard

Testing with injectWS - Type error injectWS is not a function

Open talkl opened this issue 5 months ago • 0 comments

Prerequisites

  • [x] I have written a descriptive issue title
  • [x] I have searched existing issues to ensure the bug has not already been reported

Fastify version

5.4.0

Plugin version

5.0.1

Node.js version

24.1.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

15.5

Description

App `import * as path from 'path'; import { FastifyInstance } from 'fastify'; import AutoLoad from '@fastify/autoload'; import fastifyWebsocket from '@fastify/websocket';

/* eslint-disable-next-line */ export interface AppOptions {}

export async function app(fastify: FastifyInstance, opts: AppOptions) { fastify.register(fastifyWebsocket); // Do not touch the following lines

// This loads all plugins defined in plugins // those should be support plugins that are reused // through your application fastify.register(AutoLoad, { dir: path.join(__dirname, 'plugins'), options: { ...opts }, });

// This loads all plugins defined in routes // define your routes in one of these fastify.register(AutoLoad, { dir: path.join(__dirname, 'routes'), options: { ...opts }, }); } Test import Fastify, { FastifyInstance } from 'fastify'; import { app } from './app'; import WebSocket from 'ws';

describe('API Tests', () => { let server: FastifyInstance;

beforeEach(async () => { server = Fastify(); await server.register(app); await server.ready(); });

afterEach(async () => { await server.close(); });

describe('GET /', () => { it('should respond with a message', async () => { const response = await server.inject({ method: 'GET', url: '/', });

  expect(response.json()).toEqual({ message: 'Hello API' });
});

});

describe('WebSocket /ws', () => { it('should establish a WebSocket connection', async () => { const ws = await server.injectWS('/ws'); expect(ws.readyState).toBe(WebSocket.OPEN); ws.terminate(); });

it('should echo back messages with "Server received:" prefix', async () => {
  const ws = await server.injectWS('/ws');
  const testMessage = 'Hello WebSocket!';
  
  const responsePromise = new Promise<string>((resolve) => {
    ws.on('message', (data) => {
      resolve(data.toString());
    });
  });

  ws.send(testMessage);
  const response = await responsePromise;
  expect(response).toBe(`Server received: ${testMessage}`);
  ws.terminate();
});

it('should handle multiple messages in sequence', async () => {
  const ws = await server.injectWS('/ws');
  const messages = ['First', 'Second', 'Third'];
  const receivedMessages: string[] = [];

  const responsePromise = new Promise<void>((resolve) => {
    ws.on('message', (data) => {
      receivedMessages.push(data.toString());
      if (receivedMessages.length === messages.length) {
        resolve();
      }
    });
  });

  messages.forEach(msg => ws.send(msg));
  await responsePromise;

  messages.forEach((msg, index) => {
    expect(receivedMessages[index]).toBe(`Server received: ${msg}`);
  });
  ws.terminate();
});

it('should handle connection closure', async () => {
  const ws = await server.injectWS('/ws');
  const closePromise = new Promise<void>((resolve) => {
    ws.on('close', () => {
      resolve();
    });
  });

  ws.terminate();
  await closePromise;
  expect(ws.readyState).toBe(WebSocket.CLOSED);
});

}); }); `

package.json ` { "name": "@launch-pad/source", "version": "0.0.0", "license": "MIT", "scripts": { "prepare": "husky", "dev": "nx run-many -t dev --all --parallel=true", "test": "nx run-many -t test --all" }, "lint-staged": { "*.{ts,tsx,js,jsx}": [ "prettier --write" ] }, "private": true, "devDependencies": { "@babel/preset-env": "^7.27.2", "@eslint/js": "^9.8.0", "@nx/esbuild": "21.1.2", "@nx/eslint": "21.1.2", "@nx/eslint-plugin": "21.1.2", "@nx/jest": "21.1.2", "@nx/js": "21.1.2", "@nx/node": "21.1.2", "@swc-node/register": "~1.9.1", "@swc/core": "~1.5.7", "@swc/helpers": "~0.5.11", "@swc/jest": "~0.2.36", "@types/jest": "^29.5.12", "@types/node": "~18.16.9", "@types/ws": "^8.18.1", "esbuild": "^0.19.2", "eslint": "^9.8.0", "eslint-config-prettier": "^10.0.0", "husky": "^9.1.7", "jest": "^29.7.0", "jest-environment-node": "^29.7.0", "lint-staged": "^16.1.0", "nx": "21.1.2", "prettier": "^2.6.2", "ts-jest": "^29.1.0", "ts-node": "10.9.1", "tslib": "^2.3.0", "typescript": "~5.7.2", "typescript-eslint": "^8.19.0" }, "packageManager": "[email protected]+sha512.e519b9f7639869dc8d5c3c5dfef73b3f091094b0a006d7317353c72b124e80e1afd429732e28705ad6bfa1ee879c1fce46c128ccebd3192101f43dd67c667912", "dependencies": { "@fastify/autoload": "^6.3.1", "@fastify/sensible": "^6.0.3", "@fastify/websocket": "^11.1.0", "fastify": "^5.4.0", "fastify-plugin": "^5.0.1" } }

`

I get this error: TypeError: server.injectWS is not a function

Link to code that reproduces the bug

https://github.com/talkl/launch-pad

Expected Behavior

injectWS is recognized

talkl avatar Jun 18 '25 13:06 talkl