jest-websocket-mock icon indicating copy to clipboard operation
jest-websocket-mock copied to clipboard

Usage with NodeJS and ws package

Open ajinvise opened this issue 3 years ago • 1 comments

The example from the readme works fine:

test("the server keeps track of received messages, and yields them as they come in", async () => {
    const server = new WS("ws://localhost:1234");
    const client = new WebSocket("ws://localhost:1234");

    await server.connected;
    client.send("hello");
    await expect(server).toReceiveMessage("hello");
    expect(server).toHaveReceivedMessages(["hello"]);
});

But since im working with NodeJS I need to import a specific WebSocket implementation:

import WebSocket from "ws";

test("the server keeps track of received messages, and yields them as they come in", async () => {
    const server = new WS("ws://localhost:1234");
    const client = new WebSocket("ws://localhost:1234");

    await server.connected;
    client.send("hello");
    await expect(server).toReceiveMessage("hello");
    expect(server).toHaveReceivedMessages(["hello"]);
});

That gives connect ECONNREFUSED 127.0.0.1:1234 😟

jest.config.js

module.exports = {
    transform: {
        "^.+\\.tsx?$": "ts-jest",
    },
    testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
};

Package.json

{
  "dependencies": {
    "ws": "^8.9.0"
  },
  "devDependencies": {
    "jest": "^28.1.0",
    "jest-websocket-mock": "^2.4.0",
    "ts-jest": "^28.0.2",
    "ts-node": "^10.9.1",
    "typescript": "^4.7.2"
  },
}

How can I make this work with the ws package?

ajinvise avatar Sep 30 '22 10:09 ajinvise

Same question in a StackOverflow post

ajinvise avatar Oct 03 '22 07:10 ajinvise

Hey @ajinvise ! Thanks for asking!

Have you tried the guide in the readme: https://github.com/romgain/jest-websocket-mock#using-jest-websocket-mock-to-interact-with-a-non-global-websocket-object

Please let me know if that doesn’t work for you!

romgain avatar Oct 28 '22 17:10 romgain

Thank you!! I totally missed that section 😅

ajinvise avatar Oct 31 '22 06:10 ajinvise