我正在使用这个函数来测试我的服务器,它创建了尽可能多的websocket连接,并检查我的游戏何时开始。然而,不管我分配的超时时间是多少,它都挂在JestJS上。在浏览器上- Firefox,Edge Chromium,它工作得很好。
function checkGameStart(numberOfBots) {
return new Promise((resolve, reject) => {
let clients = [];
let connection = [];
for (let i = 0; i < numberOfBots; i++) {
clients.push(new WebSocket('ws://127.0.0.1:8080'));
connection.push(false);
clients[i].onmessage = (msg) => {
let data = JSON.parse(msg.data);
if (data.title === "gameStarted") {
connection[i] = true;
checkAllClientsReady();
}
}
clients[i].onerror = (err) => reject(err);
}
function checkAllClientsReady() {
if (!(connection.includes(false))) {
resolve(true);
closeAllConnections();
}
}
function closeAllConnections() {
for (let i = 0; i < clients; i++) {
clients[i].close()
}
}
});
}有人知道为什么会发生这种事吗?我可以做些什么来确保它不会再发生。
测试代码;
test('Check the game starts', () => {
return expect(checkGameStart(4)).resolves.toBe(true);
});发布于 2021-11-10 03:40:31
我对您的代码进行了一点重构,并在测试设置中使用ws NPM包添加了一个WebSocket服务器:
const { WebSocketServer } = require('ws')
const port = 8080
const wss = new WebSocketServer({ port })
beforeAll(() => {
wss.on('connection', (ws) => {
ws.send(JSON.stringify({ title: 'gameStarted' }))
})
})
afterAll(() => {
wss.close()
})
async function checkGameStart(numberOfBots) {
await Promise.all(
new Array(numberOfBots).fill(null)
.map(() => new Promise((resolve, reject) => {
const ws = new WebSocket(`ws://localhost:${port}`)
ws.onmessage = ({ data }) => {
const { title } = JSON.parse(data)
if (title === 'gameStarted') {
ws.close()
resolve()
}
}
ws.onerror = (err) => {
ws.close()
reject(err)
}
}))
)
return true
}
test('Check the game starts', async () => {
await expect(checkGameStart(4)).resolves.toBe(true);
});
$ npx jest
PASS ./websocket.test.js
✓ Check the game starts (64 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.708 s, estimated 1 s
Ran all test suites.仅当还将Jest配置为使用jsdom 测试环境时,这才能在Jest中工作
// jest.config.js
module.exports = {
testEnvironment: "jsdom",
};否则,WebSocket构造函数将是undefined,因为它只在web浏览器环境中可用,并且在默认情况下,Jest在node环境中运行。
https://stackoverflow.com/questions/69906921
复制相似问题