Open dcrystalj opened 5 years ago
Does this help?
onBeforeLoad(win) {
initMocks()
cy.stub(win, "WebSocket", url => new MockSocket.WebSocket(url))
}
this is mostly working for me. Just trying to get the web socket to gracefully exit now.
cy.visit('/', {
onBeforeLoad: (win) => {
cy.stub(win, "WebSocket", (url) => {
MockServer = new Server(url)
MockServer.on('connection', (socket) => {
socket.send(alert)
socket.close()
})
return new WebSocket(url)
})
}
})
@theAndrewCline I'm trying to use mock-socket to mock WebSocket in my Cypress tests using your example. Everything good with the stub but I'm not able to trigger .on('connection')
callback. Any suggestion? Thanks.
@sergiop Just make sure you are mocking both the client web socket with the mock socket library and the server. The WebSocket constructor used in the above example is imported from the mock socket library.
Thanks @theAndrewCline, I was forgetting the return statement 🤦♂️😁...
About the closing of the socket, I added a .stop()
command. I don't know if it's graceful or not... but it works.
import { Server } from 'mock-socket'
Cypress.Commands.add('mockSocket', () => {
cy.on('window:before:load', (win) => {
cy.stub(win, 'WebSocket', (url) => {
const mockServer = new Server(url)
mockServer.on('connection', (socket) => {
socket.send('Connection message')
socket.close()
mockServer.stop()
})
return new WebSocket(url)
})
})
})
Does it work with cypress? I was not able to make it work within cypress env.