我有一个作为客户端连接到websocket API的模块。看起来像这样:
./ src / utils / connect-realtime-api.js
const WebSocket = require('ws') const setup = require('./helpers/setup') connectRealtimeAPI = () => { const ws = new WebSocket('wss //echo.websocket.org') ws.onopen = () => { ws.send(JSON.stringify({ "type": "reg", "channel": "stats1" })) ws.send(JSON.stringify({ "type": "reg", "channel": "stats2" })) console.log('[WebSocket] Connection opened.') } ws.onerror = (event) => { console.error('[WebSocket] An error occurred.') console.error(`Code: ${event.code}`) console.error(`Reason: ${event.reason}`) } ws.onclose = (event) => { console.error('[Websocket] Connection closed.') console.error(`Code: ${event.code}`) console.error(`Reason: ${event.reason}`) console.log('Retrying connection in 10 seconds...') setTimeout(() => connectRealtimeAPI(), 10000) } setup(ws) } module.exports = connectRealtimeAPI
setup
函数接受ws
作为参数,然后根据收到的消息执行一些操作。
./ src / utils / helpers / setup.js
const setup = (ws) => { ws.onmessage = (event) => { data = JSON.parse(event.data) // Perform actions based on order in which messages are received. } } module.exports = setup
我想使用Jest测试connect-realtime-api.js
和setup.js
。
要实现此目的,我必须通过将ws
放在ws.js
目录中并找到一种发送__mocks__
,{{ 1}},open
以及通过模拟的error
发出的消息,以触发相应的close
和ws
,然后对其进行测试。
我发现了this库,该库可以帮助我实现这一目标,但无法弄清楚该怎么做。还提供了here的实现线索,但是一旦console.logs
被成功模拟后,我仍然无法弄清楚如何发送事件/消息。
寻求有关测试实施细节的帮助。