mock-socket icon indicating copy to clipboard operation
mock-socket copied to clipboard

Cypress

Open dcrystalj opened this issue 6 years ago • 5 comments

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

dcrystalj avatar Jun 13 '19 13:06 dcrystalj

Does this help?

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

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

mornir avatar Aug 19 '19 07:08 mornir

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 avatar Aug 27 '19 20:08 theAndrewCline

@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 avatar Jul 19 '20 08:07 sergiop

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

theAndrewCline avatar Jul 19 '20 12:07 theAndrewCline

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

sergiop avatar Jul 19 '20 19:07 sergiop