javascript - Jest with WebSockets 会忽略第一个消息之后的消息吗?
问题描述
我正在尝试测试 WebSockets 服务器。onMessage 处理程序仅在第一次被调用 - 发布到服务器的任何进一步消息都不会被记录。为什么会这样?`
const WebSocket = require('ws');
const ws = new WebSocket(WEBSOCKETS_ENDPOINT);
describe('When a speed test is triggered', () => {
test('Then AWS should send the result to the client', done => {
ws.on('open', async () => {
ws.send(JSON.stringify({
message: 'start-speed-test-rbsid',
data: RBSID,
platform: "android"
}));
ws.on('message', data => {
data = JSON.parse(data)
// this gets called only once - any further messages published from the server are not logged
console.log(data)
});
})
})
afterAll(() => ws.close())
});
消息数据应记录在已发布的每条消息上
解决方案
我对回显服务器使用您的代码没有问题。
const WebSocket = require('ws');
const ws = new WebSocket('wss://echo.websocket.org');
describe('When a speed test is triggered', () => {
test('Then AWS should send the result to the client', done => {
ws.on('open', async () => {
ws.send(JSON.stringify({
message: 'start-speed-test-rbsid',
data: 'RBSID',
platform: "android"
}));
ws.on('message', data => {
// this gets called only once - any further messages published from the server are not logged
console.log(data)
});
ws.send(JSON.stringify({
message: 'start-speed-test-rbsid',
data: 'RBSID',
platform: "android"
}));
})
})
afterAll(() => ws.close());
});
还有一点是,如果你在写单元测试,并且测试涉及到网络 IO,通常建议模拟网络组件。
const WebSocket = require('ws');
jest.mock('ws', () => {
class MockedWebSocket {}
return MockedWebSocket;
});
console.log(WebSocket); // mocked
推荐阅读
- linux - 如何使用 shell 脚本创建和插入数据库?
- python-3.x - 如何删除一定长度的字符串?
- python - 稀疏矩阵与向量相乘中的列顺序
- ios - 收到通知时的默认声音和振动
- amazon-web-services - AWS:检查联合登录用户的权限
- python - Plotly:如何设置不同的标记不透明度,但为所有标记保持相同的轮廓颜色?
- ios - 如何修复:当我在搜索栏中单击“取消”时,TableView 中的 func selectRow 不起作用
- react-native - 我如何安装反应导航?
- sql-server - .Net Core Identity 种子数据:无法使用已播种的凭据登录
- python - 为什么我的稀疏张量不能转换为张量