npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

cypress-mock-websocket-plugin

v2.0.0

Published

Mock websocket requests in a cypress intercept style.

Downloads

4,260

Readme

Cypress Websocket Plugin

Mock websocket requests in a cypress intercept style.

semantic-release: conventionalcommits GitHub Workflow Status npm

The plugin allows you to write a test like:

const request = { type: 'request', payload: 'PING' }
const response = { type: 'response', payload: 'PONG'}

cy.mockWebSocket('ws://cypress-websocket/ws')
  .registerSocketRequestResponse(request, response)
  .visit('/')
  .contains('Cypress Websocket Plugin')
  .get('button')
  .click()
  .get('pre')
  .contains('PONG')

Usage

The plugin is known to work with rxjs web sockets and GraphQL Apollo client. It's recommended that you can bypass the default web socket constructor, but you can also use the browser's native web socket implementation (see below).

Setup

Import this plugin by adding it to the commands.ts file:

// cypress/support/commands.ts
import 'cypress-mock-websocket-plugin';

Here's an example how it will work with rxjs:

const isRunningInCypress = () =>
  !!window.Cypress

const getWebSocketCtor = () =>
  isRunningInCypress()
    ? window.MockedWebSocket
    : window.WebSocket

const webSocket$ = webSocket({
  url: 'ws://cypress-websocket/ws',
  WebSocketCtor: getWebSocketCtor(),
})

In your Cypress tests, mock the web socket before you call visit:

cy.mockWebSocket('ws://cypress-websocket/ws')
  .visit('/')

Changing the default web socket constructor

If for some reasons you want to use a different WebSocketCtor name than the default window.MockedWebSocket from the example, you can now change the name of the constructor:

cy.mockWebSocket('ws://cypress-websocket/ws', { webSocketCtorName: 'MyWebSocket' })

Native Web Socket API

It's now possible to use the browser's native WebSocket API. Because Cypress uses WebSockets for internal communication, you have to explicitly turn on the option for native web sockets:

cy.mockWebSocket('ws://cypress-websocket/ws', { useNative: true })

Initial response


⚠️ BREAKING CHANGE

The initial response must be moved to the options object.


If you need to mock an initial response, you can do it like this:

const initialResponse = { type: 'response', payload: 'INITIAL' }
cy.mockWebSocket('ws://cypress-websocket/ws', { connectionResponseMessage: initialResponse })

Mocking interactions (request/response style)

Mocking with static request and response:

const request = { type: 'request', payload: 'PING' }
const response = { type: 'response', payload: 'PONG'}

cy.mockWebSocket('ws://cypress-websocket/ws')
  .registerSocketRequestResponse(request, response)

If you have any fields dynamically generated by the client, e.g. access tokens, you can simply skip those properties in the request object. The plugin will partially match the expected and actual request.

Example:

// provide this to the cy.registerSocketRequestResponse
const expectedRequest = { 
  type: 'request', 
  payload: {
    content: 'Some content to match'
  }
}

// and it will match when client sends the following request:
const actualRequest = {
  type: 'request',
  payload: {
    accessToken: 'abc12345',
    content: 'Some content to match'
  }
}

The plugin uses a library called ts-pattern in order to match the requests.

If you need more control to match the request, you can pass a request handler instead of using a request object:

cy.registerSocketRequestResponse((request) => {
  //implement your logic to match the request here and return the mocked response
  return {
    type: 'response',
    payload: 'your payload'
  }
})

Mocking server events

In order to mock server events, you can simply trigger a server event like this:

cy.mockWebSocket('ws://cypress-websocket/ws')
  .visit('/')
  .contains('Cypress Websocket Plugin')
  .triggerSocketEvent({type: 'event', payload: "First Event"})
  .get('pre').contains('First Event')

Or, if you need more control (e.g. you need to provide a context specified in a previous interaction):

const correlationId = 1234
cy.mockWebSocket('ws://cypress-websocket/ws')
  .visit('/')
  .triggerSocketEvent(() => { return { type: 'event', payload: correlationId }})
  .get('pre').contains(correlationId)

Known Issues

In React 18, if you're using strict mode the useEffect hook is called twice, which does not work with the current implementation. You either have to deactivate strict mode in your tests, or you have to initialize the web socket outside of useEffect

Dependencies

This plugin was built using the following libraries:

  • Mock Socket https://github.com/thoov/mock-socket
  • ts-pattern https://github.com/gvergnaud/ts-pattern

Contributions

Any contributions are welcome. Feel free to open a ticket or create a pull request.