Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add WebSocket + ws example #111

Draft
wants to merge 12 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 24 additions & 10 deletions .github/workflows/examples.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
node-version: 18
- uses: pnpm/action-setup@v2
with:
version: 7.12.1
version: 8.15
- run: pnpm install --filter with-angular
- name: Integration tests
run: pnpm test:integration
Expand All @@ -34,7 +34,7 @@ jobs:
node-version: 18
- uses: pnpm/action-setup@v2
with:
version: 7.12.1
version: 8.15
- run: pnpm install --filter with-remix
- name: E2E tests
run: pnpm test:e2e
Expand All @@ -49,7 +49,7 @@ jobs:
node-version: 18
- uses: pnpm/action-setup@v2
with:
version: 7.12.1
version: 8.15
- run: pnpm install --filter with-svelte
- name: E2E tests
run: pnpm test:e2e
Expand All @@ -64,7 +64,7 @@ jobs:
node-version: 18
- uses: pnpm/action-setup@v2
with:
version: 7.12.1
version: 8.15
- run: pnpm install --filter with-vue
- name: Integration tests
run: pnpm test:integration
Expand All @@ -82,7 +82,7 @@ jobs:
node-version: 18
- uses: pnpm/action-setup@v2
with:
version: 7.12.1
version: 8.15
- run: pnpm install --filter with-jest
- run: pnpm test --filter with-jest

Expand All @@ -95,7 +95,7 @@ jobs:
node-version: 18
- uses: pnpm/action-setup@v2
with:
version: 7.12.1
version: 8.15
- run: pnpm install --filter with-jest-jsdom
- run: pnpm test --filter with-jest-jsdom

Expand All @@ -108,7 +108,7 @@ jobs:
node-version: 18
- uses: pnpm/action-setup@v2
with:
version: 7.12.1
version: 8.15
- run: pnpm install --filter with-vitest
- run: pnpm test --filter with-vitest

Expand All @@ -121,7 +121,7 @@ jobs:
node-version: 18
- uses: pnpm/action-setup@v2
with:
version: 7.12.1
version: 8.15
- run: pnpm install --filter with-vitest-cjs
- run: pnpm test --filter with-vitest-cjs

Expand All @@ -134,7 +134,7 @@ jobs:
node-version: 18
- uses: pnpm/action-setup@v2
with:
version: 7.12.1
version: 8.15
- run: pnpm install --filter with-playwright
- run: pnpm test --filter with-playwright

Expand All @@ -147,6 +147,20 @@ jobs:
node-version: 18
- uses: pnpm/action-setup@v2
with:
version: 7.12.1
version: 8.15
- run: pnpm install --filter with-karma
- run: pnpm test --filter with-karma

# WebSocket examples.
websocket:
runs-on: macos-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 18
- uses: pnpm/action-setup@v2
with:
version: 8.15
- run: pnpm install --filter with-websocket
- run: pnpm test --filter with-websocket
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ A collection of usage examples of [Mock Service Worker](https://github.com/mswjs
- [Angular](./examples/with-angular) (Jest, Cypress)
- Next.js
- React Native
- [Remix](./examples/with-remix) (Playwright)
- [Remix](./examples/with-remix) (React, Playwright)
- SolidJS
- [Svelte](./examples/with-svelte/) (Vitest, Playwright)
- [Vue](./examples/with-vue) (Vitest, Cypress)
Expand All @@ -21,6 +21,10 @@ A collection of usage examples of [Mock Service Worker](https://github.com/mswjs
- [Playwright](./examples/with-playwright)
- [Vitest](./examples/with-vitest) / [Vitest (CommonJS)](./examples/with-vitest-cjs)

### Other protocols

- [WHATWG WebSocket + `ws`](./examples/with-websocket/) (React, Vite, Vitest, Playwright)

### Other tools

- Storybook
Expand Down
1 change: 1 addition & 0 deletions examples/with-websocket/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_USE_MOCKS=true
18 changes: 18 additions & 0 deletions examples/with-websocket/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
26 changes: 26 additions & 0 deletions examples/with-websocket/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

/test-results
35 changes: 35 additions & 0 deletions examples/with-websocket/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# WebSocket + MSW

[Mock Service Worker](https://github.com/mswjs/msw) usage example with the global [WHATWG `WebSocket` API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) on the client and [`ws`](https://github.com/websockets/ws) on the server.

[![Edit in CodeSandbox](https://assets.codesandbox.io/github/button-edit-lime.svg)](https://codesandbox.io/p/sandbox/github/mswjs/examples/tree/main/examples/with-websocket)

- [MSW](https://mswjs.io/docs)
- [Vite](https://vitejs.dev)
- [Vitest](https://vitest.dev)
- [Playwright](https://playwright.dev/)

## General

- Describe the network behavior in [`src/mocks/handlers.ts`](./src/mocks/handlers.ts).

## Client-side

1. Create [`src/mocks/browser.ts`](./src/mocks/browser.ts) and configure the `worker` instance.
1. In [`src/main.tsx`](./src/main.tsx), start the worker instance. Defer your application's rendering by implementing a `enableMocking()` function.
1. In the [`.env`](./.env) file, control whether the application is running against mocks or the actual WebSocket server via the `VITE_USE_MOCKS` environment variable.

## Integration tests

> Node.js v18 does not yet ship a stable global `WebSocket` API. To test a code that relies on that API in Node.js, you have to polyfill the `WebSocket` class using `undici`.
>
> 1. Install `undici`.
> 1. Create [`vitest.setup.ts`](./vitest.setup.ts), import `WebSocket` from `undici` and set it as the value of `globalThis.WebSocket`.
> 1. In [`vite.config.ts`](./vite.config.ts), set the `test.setupFiles` option to point to the [`vitest.setup.ts`](./vitest.setup.ts) file.

1. Create [`src/mocks/server.ts`](./src/mocks/server.ts) and configure the `server` instance.
1. In [`src/App.test.tsx`](./src/App.test.tsx), import the `server` instance and the `api` event handler. Use them in the tests to override WebSocket client and server behaviors.

## E2E tests

Find the end-to-end test with Playwright and MSW in [`e2e/App.test.ts`](./e2e/App.test.ts). No special setup is required to run MSW in Playwright since it runs as a part of the application itself via [`src/main.tsx`](./src/main.tsx) (`enableMocking()`).
56 changes: 56 additions & 0 deletions examples/with-websocket/e2e/App.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { test, expect } from '@playwright/test'

test('sends a chat message', async ({ page }) => {
await page.goto('/')

// Send a chat message.
await page.getByRole('textbox', { name: /message/i }).fill('hello world')
await page.getByRole('button', { name: /send/i }).click()

// Must display the sent message in the UI.
await expect(page.getByRole('list', { name: /messages/i })).toHaveText(
'hello world',
)
})

test('broadcasts a chat message to all clients', async ({ page, context }) => {
await page.goto('/')

// Open the application in multiple tabs.
const secondPage = await context.newPage()
await secondPage.goto('/')

await page.bringToFront()

// Send a chat message from the first tab.
await page.getByRole('textbox', { name: /message/i }).fill('hello world')
await page.getByRole('button', { name: /send/i }).click()

// Must display the sent message for the client who sent it.
await expect(page.getByRole('list', { name: /messages/i })).toHaveText(
'hello world',
)

// Must display the sent message for the second tab.
await secondPage.bringToFront()
await expect(secondPage.getByRole('list', { name: /messages/i })).toHaveText(
'hello world',
)

// Send a message from the second tab.
await secondPage.getByRole('textbox', { name: /message/i }).fill('hi')
await secondPage.getByRole('button', { name: /send/i }).click()

// Must display the sent message for the second tab.
await expect(secondPage.getByRole('list', { name: /messages/i })).toHaveText([
'hello world',
'hi',
])

// Must display the sent message for the first tab.
await page.bringToFront()
await expect(page.getByRole('list', { name: /messages/i })).toHaveText([
'hello world',
'hi',
])
})
13 changes: 13 additions & 0 deletions examples/with-websocket/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WebSocket + ws + MSW</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
42 changes: 42 additions & 0 deletions examples/with-websocket/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "with-websocket",
"type": "module",
"scripts": {
"dev": "tsx ./server.ts",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview",
"test": "pnpm test:integration && pnpm test:e2e",
"test:integration": "vitest",
"test:e2e": "playwright test",
"postinstall": "pnpm exec playwright install"
},
"dependencies": {
"@types/ws": "^8.5.10",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"ws": "^8.16.0"
},
"devDependencies": {
"@playwright/test": "^1.43.0",
"@testing-library/jest-dom": "^6.4.2",
"@testing-library/react": "^14.2.2",
"@testing-library/user-event": "^14.4.3",
"@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22",
"@types/testing-library__jest-dom": "^5.14.5",
"@typescript-eslint/eslint-plugin": "^7.2.0",
"@typescript-eslint/parser": "^7.2.0",
"@vitejs/plugin-react": "^4.2.1",
"eslint": "^8.57.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6",
"happy-dom": "^14.7.0",
"msw": "2.3.0-ws.rc-6",
"tsx": "^4.7.2",
"typescript": "^5.2.2",
"undici": "^5.22.0",
"vite": "^5.2.0",
"vitest": "^1.4.0"
}
}
15 changes: 15 additions & 0 deletions examples/with-websocket/playwright.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { defineConfig } from '@playwright/test'

const APP_URL = 'http://localhost:5173'

export default defineConfig({
testDir: './e2e',
use: {
baseURL: APP_URL,
},
webServer: {
command: 'npm run dev',
url: APP_URL,
},
timeout: 10_000,
})
Loading
Loading