Vitest is unable to mock graphql-ws (websockets ) #7670
Unanswered
MenouerBetty
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Describe the bug
WebSocket Implementation Error in Vitest Tests
When running tests for my breadcrumbs.test.ts, I'm encountering a WebSocket implementation error:
The error occurs because
@my-bb/commonpackage (which contains our GraphQL type definitions and Apollo client setup) is trying to create a WebSocket connection through graphql-ws during test execution, even though I don't need WebSocket functionality for testing the breadcrumbs component.Attempted Solutions:
1. Mocking the ws package:
What I Want to Achieve:
I want to be able to run tests for components that import from @my-bb/common without having to set up actual WebSocket connections. The breadcrumbs component doesn't use WebSocket functionality, but because it imports from @my-bb/common (which sets up Apollo client with GraphQL), it's trying to initialize the WebSocket client.
Desired Behavior:
Reproduction
Steps to Reproduce
git clone [example-monorepo] cd [example-monorepo]Have a common package that sets up Apollo Client with GraphQL WebSocket subscriptions
Package structure
packages/
common/ # Package with shared GraphQL/Apollo setup
feature-module/ # Package that imports from common
The common package contains Apollo Client setup with WebSocket subscriptions:
// packages/common/src/client/index.js
// Apollo client setup with wsLink
// packages/feature-module/src/tests/component.test.js
import { someFunction } from '@org/common';
describe('Component', () => {
test('should work', () => {
// Test logic that doesn't use WebSocket
});
});
Create a test in the feature module that imports from the common package:
// packages/feature-module/src/tests/component.test.js
Run the test with Vitest
Observe the WebSocket implementation error even though the test isn't using WebSocket functionality:
Error: WebSocket implementation missing; on Node you can
import WebSocket from 'ws';and passwebSocketImpl: WebSockettocreateClientSystem Info
System: OS: macOS 15.3.1 CPU: (8) arm64 Apple M2 Memory: 131.97 MB / 16.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 21.7.3 - ~/.nvm/versions/node/v21.7.3/bin/node npm: 10.5.0 - ~/.nvm/versions/node/v21.7.3/bin/npm pnpm: 9.15.5 - ~/Library/pnpm/pnpm bun: 1.2.4 - ~/.bun/bin/bun Browsers: Chrome: 134.0.6998.89 Safari: 18.3 npmPackages: @vitest/coverage-v8: ^1.3.1 => 1.6.1 vitest: ^1.3.1 => 1.6.1 vitest-websocket-mock: ^0.4.0 => 0.4.0Used Package Manager
npm
Validations
Beta Was this translation helpful? Give feedback.
All reactions