Cypress plugin for mocking websockets (socket.io version 2)
Cypress 10.x
npm i -D cypress-websocket-plugin
First, integrate plugin with your Cypress setup:
- Edit file
cypress.config.ts
. Following example will let the websocket server respond tohello
by echoing it back with an argument. It will also sendping
message every 5 seconds with value coming from dynamic variable (initially set to 42). Code in the test can modify this variable to change behavior in run-time.
import { startFakeWebsocketServer } from "cypress-websocket-plugin";
export default defineConfig({
e2e: {
setupNodeEvents(on, config) {
startFakeWebsocketServer({
options: {
responses: {
'hello': ['hello', 'dear'],
},
periodicMessages: [
{"name": "ping", "args": ["$dynamicVariable"], "interval": 5000},
]
},
variables: {
"dynamicVariable": 42,
},
});
},
},
});
- Edit file
cypress/support/commands.ts
. Add:
import { addCommands } from "cypress-websocket-plugin/commands.js";
addCommands();
- port is not configurable, it's fixed as
3000
. This is on my list. - this plugin was tested and works with Socket.IO version 2 only.
Imagine you have application, that after clicking on some button will issue two messages over WebSocket:
- "hey, I just met you", args: "and this is craAAzy"
- "but here's my number", args: "so call me maybe"
This is how it would be tested with the plugin:
beforeEach(() => {
// we don't want any messages from previous test runs
cy.resetWsMessages();
});
describe('empty spec', () => {
it('passes', () => {
// cy.visit(someUrl);
// cy.get("#btn").click();
// ...
// actual check <-------
cy.expectWsMessages(
[
["hey, I just met you", "and this is craAAzy"],
["but here's my number", "so call me maybe"],
]
);
TODO (you can control values returned by the server from the test easily)
In the test following code can be used to modify options passed in Cypress configuration file:
cy.overrideWsOptions({
responses: {
'on-msg-1': ['msg-1-reply', 'arg'],
'on-msg-2': ['msg-2-reply', 'arg'],
// ...
},
periodicMessages: [
{"name": "periodic", "args": ["heartbeat", 1], "interval": 2500},
{"name": "periodic", "args": ["heartbeat", 2], "interval": 5000},
// ...
]
});