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

websocket: improve .close() #2865

Merged
merged 6 commits into from
Mar 3, 2024
Merged
Changes from 1 commit
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
53 changes: 52 additions & 1 deletion test/websocket/close.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
'use strict'

const { describe, test } = require('node:test')
const { tspl } = require('@matteo.collina/tspl')
const { describe, test, after } = require('node:test')
const assert = require('node:assert')
const { WebSocketServer } = require('ws')
const { WebSocket } = require('../..')
const { kReadyState } = require('../../lib/web/websocket/symbols')

describe('Close', () => {
test('Close with code', () => {
Expand Down Expand Up @@ -128,4 +130,53 @@ describe('Close', () => {
ws.addEventListener('open', () => ws.close(3000))
})
})

test('calling close twice will only trigger the close event once', async (t) => {
t = tspl(t, { plan: 1 })

const server = new WebSocketServer({ port: 0 })

after(() => server.close())

server.on('connection', (ws) => {
ws.on('close', (code) => {
t.strictEqual(code, 1000)
})
})

const ws = new WebSocket(`ws://localhost:${server.address().port}`)
ws.addEventListener('open', () => {
ws.close(1000)
ws.close(1000)
})

await t.completed
})

test('calling close when connection is open but close handshake has started does not result in sending the handshake again', async (t) => {
Uzlopak marked this conversation as resolved.
Show resolved Hide resolved
t = tspl(t, { plan: 1 })

const server = new WebSocketServer({ port: 0 })

after(() => server.close())

server.on('connection', (ws) => {
ws.on('close', (code) => {
t.strictEqual(code, 1000)
})
})

const ws = new WebSocket(`ws://localhost:${server.address().port}`)
ws.addEventListener('open', () => {
// .close() will start the close handshake and set the readyState to
// CLOSING
ws.close(1000)
// set the readyState to OPEN to simulate the close handshake being
// started but not yet completed
ws[kReadyState] = ws.OPEN
ws.close(1000)
})

await t.completed
})
})
Loading