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
2 changes: 1 addition & 1 deletion server/controllers/question.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ const questionController = (socket: FakeSOSocket) => {
if (result.poll) {
socket.emit('pollUpdate', { qid, poll: result.poll });
} else {
res.status(500).send('Poll data is undefined');
// res.status(500).send('Poll data is undefined'); already handled in service
}
res.json(result);
} catch (err) {
Expand Down
34 changes: 34 additions & 0 deletions server/tests/controllers/question.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -872,5 +872,39 @@ describe('Test questionController', () => {
expect(response.status).toBe(400);
expect(response.text).toBe('Invalid request');
});

it('should handle API errors when voting on a poll', async () => {
const mockReqBody = {
qid: '65e9b58910afe6e94fc6e6dc',
optionIndex: 0,
username: 'testUser',
};

// Force the voteOnPoll service to throw an exception
voteOnPollSpy.mockImplementationOnce(() => {
throw new Error('Database connection failed');
});

const response = await supertest(app).post('/question/voteOnPoll').send(mockReqBody);

expect(response.status).toBe(500);
expect(response.text).toBe('Error when voting on poll: Database connection failed');
});

it('should handle network errors when communicating with the database', async () => {
const mockReqBody = {
qid: '65e9b58910afe6e94fc6e6dc',
optionIndex: 0,
username: 'testUser',
};

// Mock a network error scenario
voteOnPollSpy.mockRejectedValueOnce(new Error('Network failure'));

const response = await supertest(app).post('/question/voteOnPoll').send(mockReqBody);

expect(response.status).toBe(500);
expect(response.text).toBe('Error when voting on poll: Network failure');
});
});
});
13 changes: 13 additions & 0 deletions server/tests/services/questions.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -609,5 +609,18 @@ describe('Question model', () => {

expect(result).toEqual({ error: 'Invalid option index' });
});

test('voteOnPoll should return an error when there is an exception during voting', async () => {
// Mock QuestionModel.findById to throw an error
jest.spyOn(QuestionModel, 'findById').mockImplementation(() => {
throw new Error('Database error');
});

// Call the function
const result = await voteOnPoll('someQuestionId', 0, 'testUser');

// Verify the function returns the expected error message
expect(result).toEqual({ error: 'Error when voting on poll' });
});
});
});