I’m using Cypress to mock my websocket. I want to write the messages to a file, but can’t do async Cypress commands in the socket handler. I’m curious if there’s any good Cypress way to do this?
export function trackWebSocketTraffic() {
let messages: string[] = []
cy.window().then((win) => {
cy.stub(win, 'WebSocketFactory').callsFake(
(url: string, handlers: WebSocketEventHandlers) => {
console.log('WebSocket URL:', url)
const webSocket = new WebSocket(url)
webSocket.onopen = handlers.onopen
webSocket.onmessage = (event: MessageEvent) => {
messages.push(event.data)
handlers.onmessage(event)
}
webSocket.onclose = (event: CloseEvent) => {
cy.writeFile('./test', messages) // !!! Can't put cy.writeFile in async handler
handlers.onclose(event)
}
return webSocket
}
)
})
}
This triggers an error:
The following error originated from your test code, not from Cypress.
> Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise.
The command that returned the promise was:
> cy.get()
The cy command you invoked inside the promise was:
> cy.writeFile()
Because Cypress commands are already promise-like, you don't need to wrap them or return your own promise.
Cypress will resolve your command with whatever the final Cypress command yields.
The reason this is an error instead of a warning is because Cypress internally queues commands serially whereas Promises execute as soon as they are invoked. Attempting to reconcile this would prevent Cypress from ever resolving.
When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.