Skip to content
Merged
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({ text: '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/);
});
});
94 changes: 94 additions & 0 deletions backend/__tests__/integration/pgMessages.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
const request = require('supertest');
const express = require('express');
const pgMessageRoutes = require('../../routes/pg-messages');
const { generateTestToken } = require('../utils/testUtils');

// Mock PG models
jest.mock('../../models/pg/Pod', () => ({
findById: jest.fn(),
isMember: jest.fn(),
addMember: jest.fn(),
}));

jest.mock('../../models/pg/Message', () => ({
findByPodId: jest.fn(),
create: jest.fn(),
findById: jest.fn(),
}));

const PGPod = require('../../models/pg/Pod');
const PGMessage = require('../../models/pg/Message');

let app;

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

afterEach(() => {
jest.clearAllMocks();
});

describe('PostgreSQL Message Routes', () => {
it('retrieves messages when user is member', async () => {
PGPod.findById.mockResolvedValue({ id: 'pod1' });
PGPod.isMember.mockResolvedValue(true);
PGMessage.findByPodId.mockResolvedValue([{ id: 1, content: 'Hello' }]);
const token = generateTestToken('user1');

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

expect(PGPod.isMember).toHaveBeenCalledWith('pod1', 'user1');
expect(res.body[0].content).toBe('Hello');
});

it('returns 401 if user is not a member', async () => {
PGPod.findById.mockResolvedValue({ id: 'pod1' });
PGPod.isMember.mockResolvedValue(false);
const token = generateTestToken('user1');

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

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

it('creates a message successfully', async () => {
PGPod.findById.mockResolvedValue({ id: 'pod1' });
PGPod.isMember.mockResolvedValue(true);
PGMessage.create.mockResolvedValue({ id: 1 });
PGMessage.findById.mockResolvedValue({ id: 1, content: 'Hi there' });
const token = generateTestToken('user1');

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

expect(PGMessage.create).toHaveBeenCalledWith('pod1', 'user1', 'Hi there');
expect(res.body.content).toBe('Hi there');
});

it('rejects message creation for non-members', async () => {
PGPod.findById.mockResolvedValue({ id: 'pod1' });
PGPod.isMember.mockResolvedValue(false);
const token = generateTestToken('user1');

const res = await request(app)
.post('/api/pg/messages/pod1')
.set('Authorization', `Bearer ${token}`)
.send({ content: 'Denied' })
.expect(401);

expect(res.body.msg).toMatch(/Not authorized/);
});
});
8 changes: 5 additions & 3 deletions backend/controllers/messageController.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,15 @@ exports.getMessages = async (req, res) => {
exports.createMessage = async (req, res) => {
try {
const { podId } = req.params;
const { text, attachments } = req.body;
const { content, text, attachments } = req.body;

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

if (!text && (!attachments || attachments.length === 0)) {
const messageContent = content || text;

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

Expand All @@ -88,7 +90,7 @@ exports.createMessage = async (req, res) => {
}

const newMessage = new Message({
text: text || '',
content: messageContent || '',
podId,
userId,
attachments: attachments || [],
Expand Down