thoov / mock-socket

Javascript mocking library for WebSockets and Socket.IO
MIT License
797 stars 118 forks source link

Cypress #263

Open dcrystalj opened 5 years ago

dcrystalj commented 5 years ago

Does it work with cypress? I was not able to make it work within cypress env.

mornir commented 5 years ago

Does this help?

onBeforeLoad(win) {
      initMocks()
      cy.stub(win, "WebSocket", url => new MockSocket.WebSocket(url))
    }

source: https://github.com/cypress-io/cypress/issues/2492

theAndrewCline commented 5 years ago

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)
        })
      }
    })
sergiop commented 4 years ago

@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.

theAndrewCline commented 4 years ago

@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.

sergiop commented 4 years ago

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)
    })
  })
})