How to test web-socket requests in Cypress. #30162
-
|
I need to intercept a web-socket connection, For this particular functionality(If I click download file button , web-socket request will trigger) this will generate auth_token cookie also. I need to establish web socket connection with auth_token cookie. And validate the web-socket messages as a success. My script : The error I'm receiving is handshake. couldn't able to establish the connection. it("Verify Zone geom file download functionality", () => { |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Your test opens a real socket, though, and the actual issue is that Cypress never waits for your async callbacks. You register cy.window().then((win) => {
return new Cypress.Promise((resolve, reject) => {
const ws = new win.WebSocket('wss://URL/v1')
ws.onopen = () => ws.send(JSON.stringify({ /* ...authToken... */ }))
ws.onmessage = (e) => {
expect(JSON.parse(e.data).service).to.equal('zonegeomfile')
ws.close()
resolve()
}
ws.onerror = reject
})
})For deterministic tests without a live backend, stub the client instead, e.g. |
Beta Was this translation helpful? Give feedback.
cy.intercept()doesn’t work with WebSockets, Cypress’s network layer only intercepts HTTP (xhr/fetch/document/etc.). WS Upgrade connections are piped straight through the proxy and never hit the interception middleware, so you can’t match, wait on, or stub them.Your test opens a real socket, though, and the actual issue is that Cypress never waits for your async callbacks. You register
onopen/onmessageand return immediately, so the test ends before a message arrives. Wrap the socket lifecycle in a promise Cypress can await: