Changer la structure de backend pour le fonctionnement des quiz

Fixes #247
This commit is contained in:
JubaAzul 2025-02-17 16:08:09 -05:00
parent 821a485a29
commit ac33483560
8 changed files with 138 additions and 138 deletions

View file

@ -63,12 +63,12 @@ describe('WebSocketService', () => {
}); });
}); });
test('endQuiz should emit end-quiz event with correct parameters', () => { test('endQuiz should emit end-questionnaire event with correct parameters', () => {
const roomName = 'testRoom'; const roomName = 'testRoom';
mockSocket = WebsocketService.connect(ENV_VARIABLES.VITE_BACKEND_SOCKET_URL); mockSocket = WebsocketService.connect(ENV_VARIABLES.VITE_BACKEND_SOCKET_URL);
WebsocketService.endQuiz(roomName); WebsocketService.endQuiz(roomName);
expect(mockSocket.emit).toHaveBeenCalledWith('end-quiz', { roomName }); expect(mockSocket.emit).toHaveBeenCalledWith('end-questionnaire', { roomName });
}); });
test('joinRoom should emit join-room event with correct parameters', () => { test('joinRoom should emit join-room event with correct parameters', () => {

View file

@ -28,7 +28,7 @@ const ManageRoom: React.FC = () => {
const [roomName, setRoomName] = useState<string>(''); const [roomName, setRoomName] = useState<string>('');
const [socket, setSocket] = useState<Socket | null>(null); const [socket, setSocket] = useState<Socket | null>(null);
const [students, setStudents] = useState<StudentType[]>([]); const [students, setStudents] = useState<StudentType[]>([]);
const quizId = useParams<{ id: string }>(); const questionnaireId = useParams<{ id: string }>();
const [quizQuestions, setQuizQuestions] = useState<QuestionType[] | undefined>(); const [quizQuestions, setQuizQuestions] = useState<QuestionType[] | undefined>();
const [quiz, setQuiz] = useState<QuizType | null>(null); const [quiz, setQuiz] = useState<QuizType | null>(null);
const [quizMode, setQuizMode] = useState<'teacher' | 'student'>('teacher'); const [quizMode, setQuizMode] = useState<'teacher' | 'student'>('teacher');
@ -37,14 +37,14 @@ const ManageRoom: React.FC = () => {
const [quizStarted, setQuizStarted] = useState(false); const [quizStarted, setQuizStarted] = useState(false);
useEffect(() => { useEffect(() => {
if (quizId.id) { if (questionnaireId.id) {
const fetchquiz = async () => { const fetchquiz = async () => {
const quiz = await ApiService.getQuiz(quizId.id as string); const quiz = await ApiService.getQuiz(questionnaireId.id as string);
if (!quiz) { if (!quiz) {
window.alert(`Une erreur est survenue.\n Le quiz ${quizId.id} n'a pas été trouvé\nVeuillez réessayer plus tard`) window.alert(`Une erreur est survenue.\n Le questionnaire ${questionnaireId.id} n'a pas été trouvé\nVeuillez réessayer plus tard`)
console.error('Quiz not found for id:', quizId.id); console.error('Questionnaire not found for id:', questionnaireId.id);
navigate('/teacher/dashboard'); navigate('/teacher/dashboard');
return; return;
} }
@ -64,12 +64,12 @@ const ManageRoom: React.FC = () => {
fetchquiz(); fetchquiz();
} else { } else {
window.alert(`Une erreur est survenue.\n Le quiz ${quizId.id} n'a pas été trouvé\nVeuillez réessayer plus tard`) window.alert(`Une erreur est survenue.\n Le questionnaire ${questionnaireId} n'a pas été trouvé\nVeuillez réessayer plus tard`)
console.error('Quiz not found for id:', quizId.id); console.error('Questionnaire not found for id:', questionnaireId.id);
navigate('/teacher/dashboard'); navigate('/teacher/dashboard');
return; return;
} }
}, [quizId]); }, [questionnaireId]);
const disconnectWebSocket = () => { const disconnectWebSocket = () => {
if (socket) { if (socket) {

View file

@ -556,14 +556,14 @@ class ApiService {
* @returns quiz if successful * @returns quiz if successful
* @returns A error string if unsuccessful, * @returns A error string if unsuccessful,
*/ */
public async getQuiz(quizId: string): Promise<QuizType | string> { public async getQuiz(questionnaireId: string): Promise<QuizType | string> {
try { try {
if (!quizId) { if (!questionnaireId) {
throw new Error(`Le quizId est requis.`); throw new Error(`Le quizId est requis.`);
} }
const url: string = this.constructRequestUrl(`/quiz/get/${quizId}`); const url: string = this.constructRequestUrl(`/questionnaire/get/${questionnaireId}`);
const headers = this.constructRequestHeaders(); const headers = this.constructRequestHeaders();
const result: AxiosResponse = await axios.get(url, { headers: headers }); const result: AxiosResponse = await axios.get(url, { headers: headers });

View file

@ -1,12 +1,12 @@
const Folders = require('../models/folders'); const Folders = require('../models/folders');
const ObjectId = require('mongodb').ObjectId; const ObjectId = require('mongodb').ObjectId;
const Quizzes = require('../models/quiz'); const Questionnaires = require('../models/questionnaires');
describe('Folders', () => { describe('Folders', () => {
let folders; let folders;
let db; let db;
let collection; let collection;
let quizzes; let questionnaires;
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); // Clear any previous mock calls jest.clearAllMocks(); // Clear any previous mock calls
@ -28,8 +28,8 @@ describe('Folders', () => {
collection: jest.fn().mockReturnValue(collection), collection: jest.fn().mockReturnValue(collection),
}; };
quizzes = new Quizzes(db); questionnaires = new Questionnaires(db);
folders = new Folders(db, quizzes); folders = new Folders(db, questionnaires);
}); });
@ -127,8 +127,8 @@ describe('Folders', () => {
it('should return the content of a folder', async () => { it('should return the content of a folder', async () => {
const folderId = '60c72b2f9b1d8b3a4c8e4d3b'; const folderId = '60c72b2f9b1d8b3a4c8e4d3b';
const content = [ const content = [
{ title: 'Quiz 1', content: [] }, { title: 'Questionnaire 1', content: [] },
{ title: 'Quiz 2', content: [] }, { title: 'Questionnaire 2', content: [] },
]; ];
// Mock the database response // Mock the database response
@ -166,8 +166,8 @@ describe('Folders', () => {
collection.deleteOne.mockResolvedValue({ deletedCount: 1 }); collection.deleteOne.mockResolvedValue({ deletedCount: 1 });
// Mock the folders.quizModel.deleteQuizzesByFolderId() // Mock the folders.questionnaireModel.deleteQuestionnairesByFolderId()
jest.spyOn(quizzes, 'deleteQuizzesByFolderId').mockResolvedValue(true); jest.spyOn(questionnaires, 'deleteQuestionnairesByFolderId').mockResolvedValue(true);
const result = await folders.delete(folderId); const result = await folders.delete(folderId);
@ -263,10 +263,10 @@ describe('Folders', () => {
const createSpy = jest.spyOn(folders, 'create').mockResolvedValue(new ObjectId()); const createSpy = jest.spyOn(folders, 'create').mockResolvedValue(new ObjectId());
// mock the folder.getContent method // mock the folder.getContent method
jest.spyOn(folders, 'getContent').mockResolvedValue([{ title: 'Quiz 1', content: [] }]); jest.spyOn(folders, 'getContent').mockResolvedValue([{ title: 'Questionnaire 1', content: [] }]);
// Mock the quizzes.create method // Mock the Questionnaires.create method
jest.spyOn(quizzes, 'create').mockResolvedValue(new ObjectId()); jest.spyOn(questionnaires, 'create').mockResolvedValue(new ObjectId());
const result = await folders.duplicate(folderId, userId); const result = await folders.duplicate(folderId, userId);
@ -276,8 +276,8 @@ describe('Folders', () => {
expect(createSpy).toHaveBeenCalledWith(duplicatedFolder.title, userId); expect(createSpy).toHaveBeenCalledWith(duplicatedFolder.title, userId);
// expect the getContent method was called // expect the getContent method was called
expect(folders.getContent).toHaveBeenCalledWith(folderId); expect(folders.getContent).toHaveBeenCalledWith(folderId);
// expect the quizzes.create method was called // expect the questionnaires.create method was called
expect(quizzes.create).toHaveBeenCalledWith('Quiz 1', [], expect.any(String), userId); expect(questionnaires.create).toHaveBeenCalledWith('Questionnaire 1', [], expect.any(String), userId);
expect(result).toBeDefined(); expect(result).toBeDefined();
}); });
@ -333,20 +333,20 @@ describe('Folders', () => {
const folderId = '60c72b2f9b1d8b3a4c8e4d3b'; const folderId = '60c72b2f9b1d8b3a4c8e4d3b';
const userId = '12345'; const userId = '12345';
const newFolderId = new ObjectId(); const newFolderId = new ObjectId();
// Mock some quizzes that are in folder.content // Mock some questionnaires that are in folder.content
const sourceFolder = { const sourceFolder = {
title: 'Test Folder', title: 'Test Folder',
content: [ content: [
{ title: 'Quiz 1', content: [] }, { title: 'Questionnaire 1', content: [] },
{ title: 'Quiz 2', content: [] }, { title: 'Questionnaire 2', content: [] },
], ],
}; };
// Mock the response from getFolderWithContent // Mock the response from getFolderWithContent
jest.spyOn(folders, 'getFolderWithContent').mockResolvedValue(sourceFolder); jest.spyOn(folders, 'getFolderWithContent').mockResolvedValue(sourceFolder);
jest.spyOn(folders, 'create').mockResolvedValue(newFolderId); jest.spyOn(folders, 'create').mockResolvedValue(newFolderId);
// Mock the response from Quiz.createQuiz // Mock the response from Questionnaire.createQuestionnaire
jest.spyOn(quizzes, 'create').mockImplementation(() => {}); jest.spyOn(questionnaires, 'create').mockImplementation(() => {});
const result = await folders.copy(folderId, userId); const result = await folders.copy(folderId, userId);
@ -384,8 +384,8 @@ describe('Folders', () => {
}; };
const content = { const content = {
content : [ content : [
{ title: 'Quiz 1', content: [] }, { title: 'Questionnaire 1', content: [] },
{ title: 'Quiz 2', content: [] }, { title: 'Questionnaire 2', content: [] },
]}; ]};
// Mock the response from getFolderById // Mock the response from getFolderById

View file

@ -1,9 +1,9 @@
const { ObjectId } = require('mongodb'); const { ObjectId } = require('mongodb');
const Quizzes = require('../models/quiz'); // Adjust the path as necessary const Questionnaires = require('../models/questionnaires'); // Adjust the path as necessary
describe('Quizzes', () => { describe('Questionnaires', () => {
let db; let db;
let quizzes; let questionnaires;
let collection; let collection;
beforeEach(() => { beforeEach(() => {
@ -28,14 +28,14 @@ describe('Quizzes', () => {
}), }),
}; };
// Initialize the Quiz model with the mocked db // Initialize the Questionnaire model with the mocked db
quizzes = new Quizzes(db); questionnaires = new Questionnaires(db);
}); });
describe('create', () => { describe('create', () => {
it('should create a new quiz if it does not exist', async () => { it('should create a new questionnaire if it does not exist', async () => {
const title = 'Test Quiz'; const title = 'Test Questionnaire';
const content = 'This is a test quiz.'; const content = 'This is a test questionnaire.';
const folderId = '507f1f77bcf86cd799439011'; const folderId = '507f1f77bcf86cd799439011';
const userId = '12345'; const userId = '12345';
@ -43,7 +43,7 @@ describe('Quizzes', () => {
collection.findOne.mockResolvedValue(null); collection.findOne.mockResolvedValue(null);
collection.insertOne.mockResolvedValue({ insertedId: new ObjectId() }); collection.insertOne.mockResolvedValue({ insertedId: new ObjectId() });
const result = await quizzes.create(title, content, folderId, userId); const result = await questionnaires.create(title, content, folderId, userId);
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled(); expect(db.getConnection).toHaveBeenCalled();
@ -59,104 +59,104 @@ describe('Quizzes', () => {
expect(result).not.toBeNull(); expect(result).not.toBeNull();
}); });
it('should throw exception if the quiz already exists', async () => { it('should throw exception if the questionnaire already exists', async () => {
const title = 'Test Quiz'; const title = 'Test Questionnaire';
const content = 'This is a test quiz.'; const content = 'This is a test questionnaire.';
const folderId = '507f1f77bcf86cd799439011'; const folderId = '507f1f77bcf86cd799439011';
const userId = '12345'; const userId = '12345';
// Mock the database response // Mock the database response
collection.findOne.mockResolvedValue({ title }); collection.findOne.mockResolvedValue({ title });
await expect(quizzes.create(title, content, folderId, userId)).rejects.toThrow(`Quiz already exists with title: ${title}, folderId: ${folderId}, userId: ${userId}`); await expect(questionnaires.create(title, content, folderId, userId)).rejects.toThrow(`Questionnaire already exists with title: ${title}, folderId: ${folderId}, userId: ${userId}`);
}); });
}); });
describe('getOwner', () => { describe('getOwner', () => {
it('should return the owner of the quiz', async () => { it('should return the owner of the questionnaire', async () => {
const quizId = '60c72b2f9b1d8b3a4c8e4d3b'; const questionnaireId = '60c72b2f9b1d8b3a4c8e4d3b';
const userId = '12345'; const userId = '12345';
// Mock the database response // Mock the database response
collection.findOne.mockResolvedValue({ userId }); collection.findOne.mockResolvedValue({ userId });
const result = await quizzes.getOwner(quizId); const result = await questionnaires.getOwner(questionnaireId);
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled(); expect(db.getConnection).toHaveBeenCalled();
expect(collection.findOne).toHaveBeenCalledWith({ _id: ObjectId.createFromHexString(quizId) }); expect(collection.findOne).toHaveBeenCalledWith({ _id: ObjectId.createFromHexString(questionnaireId) });
expect(result).toBe(userId); expect(result).toBe(userId);
}); });
}); });
describe('getContent', () => { describe('getContent', () => {
it('should return the content of the quiz', async () => { it('should return the content of the questionnaire', async () => {
const quizId = '60c72b2f9b1d8b3a4c8e4d3b'; const questionnaireId = '60c72b2f9b1d8b3a4c8e4d3b';
const content = 'This is a test quiz.'; const content = 'This is a test questionnaire.';
// Mock the database response // Mock the database response
collection.findOne.mockResolvedValue({ content }); collection.findOne.mockResolvedValue({ content });
const result = await quizzes.getContent(quizId); const result = await questionnaires.getContent(questionnaireId);
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled(); expect(db.getConnection).toHaveBeenCalled();
expect(collection.findOne).toHaveBeenCalledWith({ _id: ObjectId.createFromHexString(quizId) }); expect(collection.findOne).toHaveBeenCalledWith({ _id: ObjectId.createFromHexString(questionnaireId) });
expect(result).toEqual({ content }); expect(result).toEqual({ content });
}); });
}); });
describe('delete', () => { describe('delete', () => {
it('should delete the quiz', async () => { it('should delete the questionnaire', async () => {
const quizId = '60c72b2f9b1d8b3a4c8e4d3b'; const questionnaireId = '60c72b2f9b1d8b3a4c8e4d3b';
// Mock the database response // Mock the database response
collection.deleteOne.mockResolvedValue({deletedCount: 1}); collection.deleteOne.mockResolvedValue({deletedCount: 1});
await quizzes.delete(quizId); await questionnaires.delete(questionnaireId);
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled(); expect(db.getConnection).toHaveBeenCalled();
expect(collection.deleteOne).toHaveBeenCalledWith({ _id: ObjectId.createFromHexString(quizId) }); expect(collection.deleteOne).toHaveBeenCalledWith({ _id: ObjectId.createFromHexString(questionnaireId) });
}); });
it('should return false if the quiz does not exist', async () => { it('should return false if the questionnaire does not exist', async () => {
const quizId = '60c72b2f9b1d8b3a4c8e4d3b'; const questionnaireId = '60c72b2f9b1d8b3a4c8e4d3b';
// Mock the database response // Mock the database response
collection.deleteOne.mockResolvedValue({deletedCount: 0}); collection.deleteOne.mockResolvedValue({deletedCount: 0});
const result = await quizzes.delete(quizId); const result = await questionnaires.delete(questionnaireId);
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled(); expect(db.getConnection).toHaveBeenCalled();
expect(collection.deleteOne).toHaveBeenCalledWith({ _id: ObjectId.createFromHexString(quizId) }); expect(collection.deleteOne).toHaveBeenCalledWith({ _id: ObjectId.createFromHexString(questionnaireId) });
expect(result).toBe(false); expect(result).toBe(false);
}); });
}); });
// deleteQuizzesByFolderId // deleteQuestionnairesByFolderId
describe('deleteQuizzesByFolderId', () => { describe('deleteQuestionnairesByFolderId', () => {
it('should delete all quizzes in a folder', async () => { it('should delete all questionnaires in a folder', async () => {
const folderId = '60c72b2f9b1d8b3a4c8e4d3b'; const folderId = '60c72b2f9b1d8b3a4c8e4d3b';
// Mock the database response // Mock the database response
collection.deleteMany.mockResolvedValue({deletedCount: 2}); collection.deleteMany.mockResolvedValue({deletedCount: 2});
await quizzes.deleteQuizzesByFolderId(folderId); await questionnaires.deleteQuestionnairesByFolderId(folderId);
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled(); expect(db.getConnection).toHaveBeenCalled();
expect(collection.deleteMany).toHaveBeenCalledWith({ folderId }); expect(collection.deleteMany).toHaveBeenCalledWith({ folderId });
}); });
it('should return false if no quizzes are deleted', async () => { it('should return false if no questionnaires are deleted', async () => {
const folderId = '60c72b2f9b1d8b3a4c8e4d3b'; const folderId = '60c72b2f9b1d8b3a4c8e4d3b';
// Mock the database response // Mock the database response
collection.deleteMany.mockResolvedValue({deletedCount: 0}); collection.deleteMany.mockResolvedValue({deletedCount: 0});
const result = await quizzes.deleteQuizzesByFolderId(folderId); const result = await questionnaires.deleteQuestionnairesByFolderId(folderId);
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled(); expect(db.getConnection).toHaveBeenCalled();
@ -167,38 +167,38 @@ describe('Quizzes', () => {
// update // update
describe('update', () => { describe('update', () => {
it('should update the title and content of the quiz', async () => { it('should update the title and content of the questionnaire', async () => {
const quizId = '60c72b2f9b1d8b3a4c8e4d3b'; const questionnaireId = '60c72b2f9b1d8b3a4c8e4d3b';
const newTitle = 'Updated Quiz'; const newTitle = 'Updated Questionnaire';
const newContent = 'This is an updated quiz.'; const newContent = 'This is an updated questionnaire.';
// Mock the database response // Mock the database response
collection.updateOne.mockResolvedValue({modifiedCount: 1}); collection.updateOne.mockResolvedValue({modifiedCount: 1});
await quizzes.update(quizId, newTitle, newContent); await questionnaires.update(questionnaireId, newTitle, newContent);
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled(); expect(db.getConnection).toHaveBeenCalled();
expect(collection.updateOne).toHaveBeenCalledWith( expect(collection.updateOne).toHaveBeenCalledWith(
{ _id: ObjectId.createFromHexString(quizId) }, { _id: ObjectId.createFromHexString(questionnaireId) },
{ $set: { title: newTitle, content: newContent, updated_at: expect.any(Date) } } { $set: { title: newTitle, content: newContent, updated_at: expect.any(Date) } }
); );
}); });
it('should return false if the quiz does not exist', async () => { it('should return false if the questionnaire does not exist', async () => {
const quizId = '60c72b2f9b1d8b3a4c8e4d3b'; const questionnaireId = '60c72b2f9b1d8b3a4c8e4d3b';
const newTitle = 'Updated Quiz'; const newTitle = 'Updated Questionnaire';
const newContent = 'This is an updated quiz.'; const newContent = 'This is an updated questionnaire.';
// Mock the database response // Mock the database response
collection.updateOne.mockResolvedValue({modifiedCount: 0}); collection.updateOne.mockResolvedValue({modifiedCount: 0});
const result = await quizzes.update(quizId, newTitle, newContent); const result = await questionnaires.update(questionnaireId, newTitle, newContent);
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled(); expect(db.getConnection).toHaveBeenCalled();
expect(collection.updateOne).toHaveBeenCalledWith( expect(collection.updateOne).toHaveBeenCalledWith(
{ _id: ObjectId.createFromHexString(quizId) }, { _id: ObjectId.createFromHexString(questionnaireId) },
{ $set: { title: newTitle, content: newContent, updated_at: expect.any(Date) } } { $set: { title: newTitle, content: newContent, updated_at: expect.any(Date) } }
); );
expect(result).toBe(false); expect(result).toBe(false);
@ -207,36 +207,36 @@ describe('Quizzes', () => {
// move // move
describe('move', () => { describe('move', () => {
it('should move the quiz to a new folder', async () => { it('should move the questionnaire to a new folder', async () => {
const quizId = '60c72b2f9b1d8b3a4c8e4d3b'; const questionnaireId = '60c72b2f9b1d8b3a4c8e4d3b';
const newFolderId = '507f1f77bcf86cd799439011'; const newFolderId = '507f1f77bcf86cd799439011';
// Mock the database response // Mock the database response
collection.updateOne.mockResolvedValue({modifiedCount: 1}); collection.updateOne.mockResolvedValue({modifiedCount: 1});
await quizzes.move(quizId, newFolderId); await questionnaires.move(questionnaireId, newFolderId);
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled(); expect(db.getConnection).toHaveBeenCalled();
expect(collection.updateOne).toHaveBeenCalledWith( expect(collection.updateOne).toHaveBeenCalledWith(
{ _id: ObjectId.createFromHexString(quizId) }, { _id: ObjectId.createFromHexString(questionnaireId) },
{ $set: { folderId: newFolderId } } { $set: { folderId: newFolderId } }
); );
}); });
it('should return false if the quiz does not exist', async () => { it('should return false if the questionnaire does not exist', async () => {
const quizId = '60c72b2f9b1d8b3a4c8e4d3b'; const questionnaireId = '60c72b2f9b1d8b3a4c8e4d3b';
const newFolderId = '507f1f77bcf86cd799439011'; const newFolderId = '507f1f77bcf86cd799439011';
// Mock the database response // Mock the database response
collection.updateOne.mockResolvedValue({modifiedCount: 0}); collection.updateOne.mockResolvedValue({modifiedCount: 0});
const result = await quizzes.move(quizId, newFolderId); const result = await questionnaires.move(questionnaireId, newFolderId);
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled(); expect(db.getConnection).toHaveBeenCalled();
expect(collection.updateOne).toHaveBeenCalledWith( expect(collection.updateOne).toHaveBeenCalledWith(
{ _id: ObjectId.createFromHexString(quizId) }, { _id: ObjectId.createFromHexString(questionnaireId) },
{ $set: { folderId: newFolderId } } { $set: { folderId: newFolderId } }
); );
expect(result).toBe(false); expect(result).toBe(false);
@ -246,102 +246,102 @@ describe('Quizzes', () => {
// duplicate // duplicate
describe('duplicate', () => { describe('duplicate', () => {
it('should duplicate the quiz and return the new quiz ID', async () => { it('should duplicate the questionnaire and return the new questionnaire ID', async () => {
const quizId = '60c72b2f9b1d8b3a4c8e4d3b'; const questionnaireId = '60c72b2f9b1d8b3a4c8e4d3b';
const userId = '12345'; const userId = '12345';
const newQuizId = ObjectId.createFromTime(Math.floor(Date.now() / 1000)); // Corrected ObjectId creation const newQuestionnaireId = ObjectId.createFromTime(Math.floor(Date.now() / 1000)); // Corrected ObjectId creation
const sourceQuiz = { const sourceQuestionnaire = {
title: 'Test Quiz', title: 'Test Questionnaire',
content: 'This is a test quiz.', content: 'This is a test questionnaire.',
}; };
const createMock = jest.spyOn(quizzes, 'create').mockResolvedValue(newQuizId); const createMock = jest.spyOn(questionnaires, 'create').mockResolvedValue(newQuestionnaireId);
// mock the findOne method // mock the findOne method
jest.spyOn(collection, 'findOne') jest.spyOn(collection, 'findOne')
.mockResolvedValueOnce(sourceQuiz) // source quiz exists .mockResolvedValueOnce(sourceQuestionnaire) // source questionnaire exists
.mockResolvedValueOnce(null); // new name is not found .mockResolvedValueOnce(null); // new name is not found
const result = await quizzes.duplicate(quizId, userId); const result = await questionnaires.duplicate(questionnaireId, userId);
expect(result).toBe(newQuizId); expect(result).toBe(newQuestionnaireId);
// Ensure mocks were called correctly // Ensure mocks were called correctly
expect(createMock).toHaveBeenCalledWith( expect(createMock).toHaveBeenCalledWith(
sourceQuiz.title + ' (1)', sourceQuestionnaire.title + ' (1)',
sourceQuiz.content, sourceQuestionnaire.content,
undefined, undefined,
userId userId
); );
}); });
// Add test case for quizExists (name with number in parentheses) // Add test case for questionnaireExists (name with number in parentheses)
it('should create a new title if the quiz title already exists and ends with " (1)"', async () => { it('should create a new title if the questionnaire title already exists and ends with " (1)"', async () => {
const quizId = '60c72b2f9b1d8b3a4c8e4d3b'; const questionnaireId = '60c72b2f9b1d8b3a4c8e4d3b';
const userId = '12345'; const userId = '12345';
const newQuizId = ObjectId.createFromTime(Math.floor(Date.now() / 1000)); const newQuestionanireId = ObjectId.createFromTime(Math.floor(Date.now() / 1000));
const sourceQuiz = { const sourceQuestionnaire = {
title: 'Test Quiz (1)', title: 'Test Questionnaire (1)',
content: 'This is a test quiz.', content: 'This is a test questionnaire.',
}; };
const createMock = jest.spyOn(quizzes, 'create').mockResolvedValue(newQuizId); const createMock = jest.spyOn(questionnaires, 'create').mockResolvedValue(newQuestionanireId);
// mock the findOne method // mock the findOne method
jest.spyOn(collection, 'findOne') jest.spyOn(collection, 'findOne')
.mockResolvedValueOnce(sourceQuiz) // source quiz exists .mockResolvedValueOnce(sourceQuestionnaire) // source questionnaire exists
.mockResolvedValueOnce(null); // new name is not found .mockResolvedValueOnce(null); // new name is not found
const result = await quizzes.duplicate(quizId, userId); const result = await questionnaires.duplicate(questionnaireId, userId);
expect(result).toBe(newQuizId); expect(result).toBe(newQuestionanireId);
// Ensure mocks were called correctly // Ensure mocks were called correctly
expect(createMock).toHaveBeenCalledWith( expect(createMock).toHaveBeenCalledWith(
'Test Quiz (2)', 'Test Questionnaire (2)',
sourceQuiz.content, sourceQuestionnaire.content,
undefined, undefined,
userId userId
); );
}); });
// test case for duplication of "C (1)" but "C (2)" already exists, so it should create "C (3)" // test case for duplication of "C (1)" but "C (2)" already exists, so it should create "C (3)"
it('should create a new title if the quiz title already exists and ends with " (n)" but the incremented n also exists', async () => { it('should create a new title if the questionnaire title already exists and ends with " (n)" but the incremented n also exists', async () => {
const quizId = '60c72b2f9b1d8b3a4c8e4d3b'; const questionnaireId = '60c72b2f9b1d8b3a4c8e4d3b';
const userId = '12345'; const userId = '12345';
const newQuizId = ObjectId.createFromTime(Math.floor(Date.now() / 1000)); const newQuestionnaireId = ObjectId.createFromTime(Math.floor(Date.now() / 1000));
const sourceQuiz = { const sourceQuestionnaire = {
title: 'Test Quiz (1)', title: 'Test Questionnaire (1)',
content: 'This is a test quiz.', content: 'This is a test questionnaire.',
}; };
const createMock = jest.spyOn(quizzes, 'create').mockResolvedValue(newQuizId); const createMock = jest.spyOn(questionnaires, 'create').mockResolvedValue(newQuestionnaireId);
// mock the findOne method // mock the findOne method
jest.spyOn(collection, 'findOne') jest.spyOn(collection, 'findOne')
.mockResolvedValueOnce(sourceQuiz) // source quiz exists .mockResolvedValueOnce(sourceQuestionnaire) // source questionnaire exists
.mockResolvedValueOnce({ title: 'Test Quiz (2)' }) // new name collision .mockResolvedValueOnce({ title: 'Test Questionnaire (2)' }) // new name collision
.mockResolvedValueOnce(null); // final new name is not found .mockResolvedValueOnce(null); // final new name is not found
const result = await quizzes.duplicate(quizId, userId); const result = await questionnaires.duplicate(questionnaireId, userId);
expect(result).toBe(newQuizId); expect(result).toBe(newQuestionnaireId);
// Ensure mocks were called correctly // Ensure mocks were called correctly
expect(createMock).toHaveBeenCalledWith( expect(createMock).toHaveBeenCalledWith(
'Test Quiz (3)', 'Test Questionnaire (3)',
sourceQuiz.content, sourceQuestionnaire.content,
undefined, undefined,
userId userId
); );
}); });
it('should throw an error if the quiz does not exist', async () => { it('should throw an error if the questionnaire does not exist', async () => {
const quizId = '60c72b2f9b1d8b3a4c8e4d3b'; const questionnaireId = '60c72b2f9b1d8b3a4c8e4d3b';
const userId = '12345'; const userId = '12345';
// Mock the response from getContent // Mock the response from getContent
jest.spyOn(quizzes, 'getContent').mockResolvedValue(null); jest.spyOn(questionnaires, 'getContent').mockResolvedValue(null);
await expect(quizzes.duplicate(quizId, userId)).rejects.toThrow(); await expect(questionnaires.duplicate(questionnaireId, userId)).rejects.toThrow();
}); });
}); });
}); });

View file

@ -154,11 +154,11 @@ describe("websocket server", () => {
}); });
}); });
test("should end quiz", (done) => { test("should end questionnaire", (done) => {
teacherSocket.emit("end-quiz", { teacherSocket.emit("end-questionnaire", {
roomName: "ROOM1", roomName: "ROOM1",
}); });
studentSocket.on("end-quiz", () => { studentSocket.on("end-questionnaire", () => {
done(); done();
}); });
}); });

View file

@ -1,6 +1,6 @@
const Users = require('../models/users'); const Users = require('../models/users');
const bcrypt = require('bcrypt'); const bcrypt = require('bcrypt');
const Quizzes = require('../models/quiz'); const Questionnaires = require('../models/questionnaires');
const Folders = require('../models/folders'); const Folders = require('../models/folders');
const { ObjectId } = require('mongodb'); const { ObjectId } = require('mongodb');
@ -26,8 +26,8 @@ describe('Users', () => {
deleteOne: jest.fn(), deleteOne: jest.fn(),
}; };
const quizModel = new Quizzes(db); const questionnaireModel = new Questionnaires(db);
const foldersModel = new Folders(db, quizModel); const foldersModel = new Folders(db, questionnaireModel);
users = new Users(db, foldersModel); users = new Users(db, foldersModel);
}); });

View file

@ -24,7 +24,7 @@ const usersController = require('./controllers/users.js');
const usersControllerInstance = new usersController(userModel); const usersControllerInstance = new usersController(userModel);
const foldersController = require('./controllers/folders.js'); const foldersController = require('./controllers/folders.js');
const foldersControllerInstance = new foldersController(foldersModel); const foldersControllerInstance = new foldersController(foldersModel);
const questionnaireController = require('./controllers/questionnaire.js'); const questionnaireController = require('./controllers/questionnaires.js');
const questionnaireControllerInstance = new questionnaireController(questionnaireModel, foldersModel); const questionnaireControllerInstance = new questionnaireController(questionnaireModel, foldersModel);
const imagesController = require('./controllers/images.js'); const imagesController = require('./controllers/images.js');
const imagesControllerInstance = new imagesController(imageModel); const imagesControllerInstance = new imagesController(imageModel);