Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
96 changes: 96 additions & 0 deletions backend/__tests__/integration/messages.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
const request = require('supertest');
const express = require('express');
// eslint-disable-next-line no-unused-vars
const mongoose = require('mongoose');
const messageRoutes = require('../../routes/messages');
const User = require('../../models/User');
const Pod = require('../../models/Pod');
const Message = require('../../models/Message');
const {
setupMongoDb,
closeMongoDb,
clearMongoDb,
generateTestToken,
createTestUser,
createTestPod,
createTestMessage,
} = require('../utils/testUtils');

describe('Message Routes Integration Tests', () => {
let app;

beforeAll(async () => {
await setupMongoDb();
app = express();
app.use(express.json());
process.env.JWT_SECRET = 'test-jwt-secret';
app.use('/api/messages', messageRoutes);
});

afterAll(async () => {
await closeMongoDb();
});

afterEach(async () => {
await clearMongoDb();
});

it('should get messages for a pod when user is a member', async () => {
const user = await createTestUser(User);
const pod = await createTestPod(Pod, user._id);
await createTestMessage(Message, pod._id, user._id, { content: 'Hello' });
const token = generateTestToken(user._id);

const response = await request(app)
.get(`/api/messages/${pod._id}`)
.set('Authorization', `Bearer ${token}`)
.expect(200);

expect(Array.isArray(response.body)).toBe(true);
expect(response.body[0].content || response.body[0].text).toBe('Hello');
});

it('should return 401 if user is not a member of the pod', async () => {
const creator = await createTestUser(User, { username: 'creator' });
const pod = await createTestPod(Pod, creator._id);
const outsider = await createTestUser(User, { username: 'outsider', email: 'out@example.com' });
const token = generateTestToken(outsider._id);

const response = await request(app)
.get(`/api/messages/${pod._id}`)
.set('Authorization', `Bearer ${token}`)
.expect(401);

expect(response.body.msg).toMatch(/Not authorized/);
});

it('should create a message successfully', async () => {
const user = await createTestUser(User);
const pod = await createTestPod(Pod, user._id);
const token = generateTestToken(user._id);

const response = await request(app)
.post(`/api/messages/${pod._id}`)
.set('Authorization', `Bearer ${token}`)
.send({ content: 'Hi there' })
.expect(200);

expect(response.body.text || response.body.content).toBe('Hi there');
const messages = await Message.find({ podId: pod._id });
expect(messages.length).toBe(1);
});

it('should return 400 when message text and attachments are missing', async () => {
const user = await createTestUser(User);
const pod = await createTestPod(Pod, user._id);
const token = generateTestToken(user._id);

const response = await request(app)
.post(`/api/messages/${pod._id}`)
.set('Authorization', `Bearer ${token}`)
.send({})
.expect(400);

expect(response.body.msg).toMatch(/required/);
});
});
149 changes: 149 additions & 0 deletions backend/__tests__/integration/pgMessages.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
const request = require('supertest');
const express = require('express');
const { newDb } = require('pg-mem');
const { generateTestToken } = require('../utils/testUtils');

// Mock the PostgreSQL pool with pg-mem
jest.mock('../../config/db-pg', () => {
const { newDb } = require('pg-mem');
const mockDb = newDb();
mockDb.public.registerFunction({
name: 'gen_random_uuid',
implementation: () => require('crypto').randomUUID(),
});
const { Pool } = mockDb.adapters.createPg();
const pool = new Pool();
return {
pool,
connectPG: async () => pool,
};
});

const { pool: pgPool } = require('../../config/db-pg');

const pgMessageRoutes = require('../../routes/pg-messages');
const PGPod = require('../../models/pg/Pod');

let app;

beforeAll(async () => {
// Create required tables
await pgPool.query(`
CREATE TABLE pods (
id VARCHAR(24) PRIMARY KEY,
name VARCHAR(100) NOT NULL,
description TEXT,
type VARCHAR(50) NOT NULL,
created_by VARCHAR(24) NOT NULL,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
`);
await pgPool.query(`
CREATE TABLE pod_members (
pod_id VARCHAR(24) NOT NULL,
user_id VARCHAR(24) NOT NULL,
joined_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
UNIQUE(pod_id, user_id)
);
`);
await pgPool.query(`
CREATE TABLE messages (
id SERIAL PRIMARY KEY,
pod_id VARCHAR(24) NOT NULL,
user_id VARCHAR(24) NOT NULL,
content TEXT NOT NULL,
message_type VARCHAR(20) DEFAULT 'text',
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
`);
await pgPool.query(`
CREATE TABLE users (
_id VARCHAR(24) PRIMARY KEY,
username VARCHAR(100) NOT NULL,
profile_picture TEXT
);
`);

process.env.JWT_SECRET = 'test-secret';
app = express();
app.use(express.json());
app.use('/api/pg/messages', pgMessageRoutes);

// Mock PGPod methods that rely on unsupported SQL features in pg-mem
jest.spyOn(PGPod, 'findById').mockImplementation(async (id) => {
const podRes = await pgPool.query('SELECT * FROM pods WHERE id = $1', [id]);
if (!podRes.rows.length) return null;
const membersRes = await pgPool.query('SELECT user_id FROM pod_members WHERE pod_id = $1', [id]);
return { ...podRes.rows[0], members: membersRes.rows.map((m) => m.user_id) };
});
jest.spyOn(PGPod, 'isMember').mockImplementation(async (podId, userId) => {
const res = await pgPool.query('SELECT 1 FROM pod_members WHERE pod_id = $1 AND user_id = $2', [podId, userId]);
return res.rows.length > 0;
});
});

afterEach(async () => {
await pgPool.query('DELETE FROM messages');
await pgPool.query('DELETE FROM pod_members');
await pgPool.query('DELETE FROM pods');
await pgPool.query('DELETE FROM users');
});

afterAll(async () => {
await pgPool.end();
});

const createUser = async (id, username) => {
await pgPool.query('INSERT INTO users (_id, username) VALUES ($1, $2)', [id, username]);
};

const createPod = async (userId, name = 'Pod 1') => {
const podId = Math.random().toString(16).slice(2, 10);
await pgPool.query(
'INSERT INTO pods (id, name, description, type, created_by) VALUES ($1, $2, $3, $4, $5)',
[podId, name, 'Test', 'chat', userId],
);
await pgPool.query('INSERT INTO pod_members (pod_id, user_id) VALUES ($1, $2)', [podId, userId]);
return podId;
};

describe('PostgreSQL Message Routes', () => {
test('should create and fetch messages', async () => {
const userId = 'user1';
await createUser(userId, 'User1');
const token = generateTestToken(userId);
const podId = await createPod(userId);

const createRes = await request(app)
.post(`/api/pg/messages/${podId}`)
.set('Authorization', `Bearer ${token}`)
.send({ content: 'hello pg' })
.expect(200);
expect(createRes.body.content).toBe('hello pg');

const getRes = await request(app)
.get(`/api/pg/messages/${podId}`)
.set('Authorization', `Bearer ${token}`)
.expect(200);
expect(getRes.body.length).toBe(1);
expect(getRes.body[0].content).toBe('hello pg');
});

test('should not allow non-members to create messages', async () => {
const ownerId = 'owner';
const otherId = 'outsider';
await createUser(ownerId, 'Owner');
await createUser(otherId, 'Other');
const ownerToken = generateTestToken(ownerId);
const otherToken = generateTestToken(otherId);
const podId = await createPod(ownerId);

await request(app)
.post(`/api/pg/messages/${podId}`)
.set('Authorization', `Bearer ${otherToken}`)
.send({ content: 'nope' })
.expect(401);
});
});
16 changes: 12 additions & 4 deletions backend/controllers/messageController.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,21 @@ exports.getMessages = async (req, res) => {
exports.createMessage = async (req, res) => {
try {
const { podId } = req.params;
const { text, attachments } = req.body;
const {
content,
text,
attachments,
messageType = 'text',
} = req.body;

const finalContent = content || text;

if (!podId) {
return res.status(400).json({ msg: 'Pod ID is required' });
}

if (!text && (!attachments || attachments.length === 0)) {
return res.status(400).json({ msg: 'Message text or attachments are required' });
if (!finalContent && (!attachments || attachments.length === 0)) {
return res.status(400).json({ msg: 'Message content or attachments are required' });
}

// Check if pod exists
Expand All @@ -88,9 +95,10 @@ exports.createMessage = async (req, res) => {
}

const newMessage = new Message({
text: text || '',
content: finalContent || '',
podId,
userId,
messageType,
attachments: attachments || [],
});

Expand Down
Loading