jest-websocket-mock
jest-websocket-mock copied to clipboard
Usage with NodeJS and ws package
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?
Same question in a StackOverflow post
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!
Thank you!! I totally missed that section 😅