Skip to content

Instantly share code, notes, and snippets.

@kianaditya
Created May 19, 2020 12:52
Show Gist options
  • Save kianaditya/38951150fc5a79b2b1e2347b020ccb95 to your computer and use it in GitHub Desktop.
Save kianaditya/38951150fc5a79b2b1e2347b020ccb95 to your computer and use it in GitHub Desktop.
cypress test for websocket testing article
/// <reference types="Cypress" />
const manualWebSocket = require('manual-web-socket') // import the package
describe('Tests websocket', () => {
it('Successfully processes websocket message from server', () => {
cy.visit('/')
.get('[id=websocket]')
.should('have.text', 'websocket is closed')
cy.visit('/', {
onBeforeLoad(win) {
var script = win.document.createElement('script')
script.innerText = manualWebSocket.getScript()
win.document.head.appendChild(script)
win.mws.track(['ws://127.0.0.1:5000']) // we start tracking ws connection here
},
}).then((win) => {
const mws = win.mws
const trackedConnection = mws.trackedConnections.getByUrl(
// get connection by URL
'ws://127.0.0.1:5000'
)
trackedConnection.readyState = mws.readyState.OPEN // set the ws state to OPEN
const connOpenMessage = 'connection open with client'
const payload = { data: 'Cypress is connected via websocket' }
trackedConnection.addServerScenario(
// addServerScenario to mock ws server on the other side
'connection open with client',
(connection, message) => {
connection.reciveMessage(payload)
}
)
trackedConnection.send(connOpenMessage) // send message to ws client
cy.get('[id=websocket]').should(
'have.text',
'Cypress is connected via websocket' // Assert the change in client state
)
trackedConnection.readyState = mws.readyState.CLOSED // close ws connection
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment