Files
adopt-a-street/backend/__tests__/socketio.test.js
William Valentin 780147eabf fix: improve test infrastructure and resolve mocking issues
- Fix Jest test runner configuration (was using bun test)
- Implement proper CouchDB service mocking in jest.preSetup.js
- Update errorhandling.test.js to use test app instead of real server
- Fix browserslist deprecation warnings
- Skip CouchDB initialization during test environment
- 22/22 Post model tests now passing
- 7/38 error handling tests now passing

🤖 Generated with [AI Assistant]

Co-Authored-By: AI Assistant <noreply@ai-assistant.com>
2025-11-03 12:13:16 -08:00

288 lines
7.7 KiB
JavaScript

const request = require("supertest");
const socketIoClient = require("socket.io-client");
const jwt = require("jsonwebtoken");
const { app, server, io } = require("../server");
const User = require("../models/User");
const Event = require("../models/Event");
const Post = require("../models/Post");
const { generateTestId } = require('./utils/idGenerator');
describe("Socket.IO Real-time Features", () => {
let server;
let io;
let clientSocket;
let testUser;
let authToken;
beforeAll(async () => {
// Start server if not already started
if (!server.listening) {
server.listen(0); // Use random port
}
// Create test user
testUser = await User.create({
name: "Test User",
email: "test@example.com",
password: "password123",
});
// Generate auth token
authToken = jwt.sign(
{ user: { id: testUser._id } },
process.env.JWT_SECRET || "test_secret"
);
});
afterAll(async () => {
if (clientSocket) {
clientSocket.disconnect();
}
server.close();
});
beforeEach((done) => {
// Connect client socket with authentication
clientSocket = socketIoClient(`http://localhost:${server.address().port}`, {
auth: { token: authToken },
});
clientSocket.on("connect", () => {
done();
});
clientSocket.on("connect_error", (err) => {
done(err);
});
});
afterEach(() => {
if (clientSocket && clientSocket.connected) {
clientSocket.disconnect();
}
});
describe("Socket Authentication", () => {
test("should connect with valid token", (done) => {
expect(clientSocket.connected).toBe(true);
done();
});
test("should reject connection with invalid token", (done) => {
const invalidSocket = socketIoClient(
`http://localhost:${server.address().port}`,
{
auth: { token: "invalid_token" },
}
);
invalidSocket.on("connect_error", (err) => {
expect(err.message).toBe("Authentication error: Invalid token");
invalidSocket.disconnect();
done();
});
});
test("should reject connection without token", (done) => {
const noTokenSocket = socketIoClient(
`http://localhost:${server.address().port}`
);
noTokenSocket.on("connect_error", (err) => {
expect(err.message).toBe("Authentication error: No token provided");
noTokenSocket.disconnect();
done();
});
});
});
describe("Event Participation", () => {
let testEvent;
beforeEach(async () => {
testEvent = await Event.create({
title: "Test Event",
description: "Test Description",
date: new Date(Date.now() + 86400000), // Tomorrow
location: "Test Location",
participants: [],
});
});
test("should join event room", (done) => {
clientSocket.emit("joinEvent", testEvent._id.toString());
// Verify socket joined room by checking server logs
setTimeout(() => {
// The socket should have joined the event room
expect(clientSocket.rooms.has(`event_${testEvent._id}`)).toBe(true);
done();
}, 100);
});
test("should receive event updates in room", (done) => {
clientSocket.emit("joinEvent", testEvent._id.toString());
// Listen for updates
clientSocket.on("update", (data) => {
expect(data).toBe("Event status updated to ongoing");
done();
});
// Simulate event update
setTimeout(() => {
clientSocket.emit("eventUpdate", {
eventId: testEvent._id.toString(),
message: "Event status updated to ongoing",
});
}, 100);
});
test("should not receive updates for events not joined", (done) => {
const anotherEventId = generateTestId();
// Listen for updates (should not receive any)
let updateReceived = false;
clientSocket.on("update", () => {
updateReceived = true;
});
// Send update for event not joined
setTimeout(() => {
clientSocket.emit("eventUpdate", {
eventId: anotherEventId,
message: "This should not be received",
});
// Check after delay that no update was received
setTimeout(() => {
expect(updateReceived).toBe(false);
done();
}, 100);
}, 100);
});
});
describe("Post Interactions", () => {
let testPost;
beforeEach(async () => {
testPost = await Post.create({
user: {
userId: testUser._id,
name: testUser.name,
},
content: "Test post content",
likes: [],
commentsCount: 0,
});
});
test("should join post room", (done) => {
clientSocket.emit("joinPost", testPost._id.toString());
setTimeout(() => {
expect(clientSocket.rooms.has(`post_${testPost._id}`)).toBe(true);
done();
}, 100);
});
test("should handle multiple room joins", (done) => {
Event.create({
title: "Another Event",
description: "Another Description",
date: new Date(Date.now() + 86400000),
location: "Another Location",
participants: [],
}).then((testEvent) => {
clientSocket.emit("joinEvent", testEvent._id.toString());
clientSocket.emit("joinPost", testPost._id.toString());
setTimeout(() => {
expect(clientSocket.rooms.has(`event_${testEvent._id}`)).toBe(true);
expect(clientSocket.rooms.has(`post_${testPost._id}`)).toBe(true);
done();
}, 100);
});
});
});
describe("Connection Stability", () => {
test("should handle disconnection gracefully", (done) => {
const disconnectSpy = jest.spyOn(console, "log");
clientSocket.disconnect();
setTimeout(() => {
expect(disconnectSpy).toHaveBeenCalledWith(
expect.stringContaining("Client disconnected:")
);
disconnectSpy.mockRestore();
done();
}, 100);
});
test("should maintain connection under load", async () => {
const startTime = Date.now();
const messageCount = 100;
for (let i = 0; i < messageCount; i++) {
await new Promise((resolve) => {
clientSocket.emit("eventUpdate", {
eventId: generateTestId(),
message: `Test message ${i}`,
});
setTimeout(resolve, 10);
});
}
const endTime = Date.now();
const duration = endTime - startTime;
// Should complete within reasonable time (less than 5 seconds)
expect(duration).toBeLessThan(5000);
expect(clientSocket.connected).toBe(true);
});
});
describe("Concurrent Connections", () => {
test("should handle multiple simultaneous connections", async () => {
const clients = [];
const connectionPromises = [];
// Create 10 concurrent connections
for (let i = 0; i < 10; i++) {
const promise = new Promise((resolve) => {
const client = socketIoClient(
`http://localhost:${server.address().port}`,
{
auth: { token: authToken },
}
);
client.on("connect", () => {
clients.push(client);
resolve();
});
client.on("connect_error", (err) => {
resolve(err);
});
});
connectionPromises.push(promise);
}
await Promise.all(connectionPromises);
// All connections should succeed
expect(clients.length).toBe(10);
clients.forEach((client) => {
expect(client.connected).toBe(true);
});
// Clean up
clients.forEach((client) => client.disconnect());
});
});
});