Compare commits

...

2 commits

Author SHA1 Message Date
Philippe Côté
a83ada1df4
Merge 51ae004c5b into ee7a7a0544 2025-03-24 15:25:17 -04:00
Philippe
51ae004c5b share by email function removed 2025-03-24 15:25:13 -04:00
5 changed files with 81 additions and 322 deletions

View file

@ -1,74 +0,0 @@
import React from 'react';
import { render, fireEvent, screen, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import ShareQuizModal from '../../../components/ShareQuizModal/ShareQuizModal';
import { QuizType } from '../../../Types/QuizType';
import ApiService from '../../../services/ApiService';
jest.mock('../../../services/ApiService');
Object.assign(navigator, {
clipboard: {
writeText: jest.fn().mockResolvedValue(undefined),
},
});
window.alert = jest.fn();
const mockQuiz: QuizType = {
_id: '1',
title: 'Sample Quiz',
content: ['::Question 1:: What is 2+2? {=4 ~3 ~5}'],
folderId: 'folder1',
folderName: 'Sample Folder',
userId: 'user1',
created_at: new Date(),
updated_at: new Date(),
};
describe('ShareQuizModal', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should call ApiService.ShareQuiz when sharing by email', async () => {
render(<ShareQuizModal quiz={mockQuiz} />);
const shareButton = screen.getByRole('button', { name: /partager quiz/i });
fireEvent.click(shareButton);
const emailButton = screen.getByRole('button', { name: /partager par email/i });
fireEvent.click(emailButton);
const email = 'test@example.com';
window.prompt = jest.fn().mockReturnValue(email);
await fireEvent.click(emailButton);
expect(ApiService.ShareQuiz).toHaveBeenCalledWith(mockQuiz._id, email);
});
it('copies the correct URL to the clipboard when sharing by URL', async () => {
render(<ShareQuizModal quiz={mockQuiz} />);
// Open the modal
const shareButton = screen.getByRole('button', { name: /partager quiz/i });
fireEvent.click(shareButton);
// Click the "Share by URL" button
const shareByUrlButton = screen.getByRole('button', { name: /partager par url/i });
fireEvent.click(shareByUrlButton);
// Check if the correct URL was copied
const expectedUrl = `${window.location.origin}/teacher/share/${mockQuiz._id}`;
expect(navigator.clipboard.writeText).toHaveBeenCalledWith(expectedUrl);
// Check if the alert is shown
await waitFor(() => {
expect(window.alert).toHaveBeenCalledWith('URL a été copiée avec succès.');
});
});
});

View file

@ -1,83 +0,0 @@
import axios from 'axios';
import ApiService from '../../services/ApiService';
import { ENV_VARIABLES } from '../../constants';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;
describe('ApiService', () => {
describe('shareQuiz', () => {
it('should call the API to share a quiz and return true on success', async () => {
const quizId = '123';
const email = 'test@example.com';
const response = { status: 200 };
mockedAxios.put.mockResolvedValue(response);
const result = await ApiService.ShareQuiz(quizId, email);
expect(mockedAxios.put).toHaveBeenCalledWith(
`${ENV_VARIABLES.VITE_BACKEND_URL}/api/quiz/Share`,
{ quizId, email },
{ headers: expect.any(Object) }
);
expect(result).toBe(true);
});
it('should return an error message if the API call fails', async () => {
const quizId = '123';
const email = 'test@example.com';
const errorMessage = 'An unexpected error occurred.';
mockedAxios.put.mockRejectedValue({ response: { data: { error: errorMessage } } });
const result = await ApiService.ShareQuiz(quizId, email);
expect(result).toBe(errorMessage);
});
it('should return a generic error message if an unexpected error occurs', async () => {
const quizId = '123';
const email = 'test@example.com';
mockedAxios.put.mockRejectedValue(new Error('Unexpected error'));
const result = await ApiService.ShareQuiz(quizId, email);
expect(result).toBe('An unexpected error occurred.');
});
});
describe('getSharedQuiz', () => {
it('should call the API to get a shared quiz and return the quiz data on success', async () => {
const quizId = '123';
const quizData = 'Quiz data';
const response = { status: 200, data: { data: quizData } };
mockedAxios.get.mockResolvedValue(response);
const result = await ApiService.getSharedQuiz(quizId);
expect(mockedAxios.get).toHaveBeenCalledWith(
`${ENV_VARIABLES.VITE_BACKEND_URL}/api/quiz/getShare/${quizId}`,
{ headers: expect.any(Object) }
);
expect(result).toBe(quizData);
});
it('should return an error message if the API call fails', async () => {
const quizId = '123';
const errorMessage = 'An unexpected error occurred.';
mockedAxios.get.mockRejectedValue({ response: { data: { error: errorMessage } } });
const result = await ApiService.getSharedQuiz(quizId);
expect(result).toBe(errorMessage);
});
it('should return a generic error message if an unexpected error occurs', async () => {
const quizId = '123';
mockedAxios.get.mockRejectedValue(new Error('Unexpected error'));
const result = await ApiService.getSharedQuiz(quizId);
expect(result).toBe('An unexpected error occurred.');
});
});
});

View file

@ -1,71 +0,0 @@
import React, { useState } from 'react';
import { Dialog, DialogTitle, DialogActions, Button, Tooltip, IconButton } from '@mui/material';
import { Share } from '@mui/icons-material';
import { QuizType } from '../../Types/QuizType';
import ApiService from '../../services/ApiService';
interface ShareQuizModalProps {
quiz: QuizType;
}
const ShareQuizModal: React.FC<ShareQuizModalProps> = ({ quiz }) => {
const [open, setOpen] = useState(false);
const handleOpenModal = () => setOpen(true);
const handleCloseModal = () => setOpen(false);
const handleShareByEmail = async () => {
const email = prompt(`Veuillez saisir l'email de la personne avec qui vous souhaitez partager ce quiz`, "");
if (email) {
try {
const result = await ApiService.ShareQuiz(quiz._id, email);
if (!result) {
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`);
return;
}
window.alert(`Quiz partagé avec succès!`);
} catch (error) {
console.error('Erreur lors du partage du quiz:', error);
}
}
handleCloseModal();
};
const handleShareByUrl = () => {
const quizUrl = `${window.location.origin}/teacher/share/${quiz._id}`;
navigator.clipboard.writeText(quizUrl)
.then(() => {
window.alert('URL a été copiée avec succès.');
})
.catch(() => {
window.alert('Une erreur est survenue lors de la copie de l\'URL.');
});
handleCloseModal();
};
return (
<>
<Tooltip title="Partager quiz" placement="top">
<IconButton color="primary" onClick={handleOpenModal} aria-label="partager quiz">
<Share />
</IconButton>
</Tooltip>
<Dialog open={open} onClose={handleCloseModal} fullWidth maxWidth="xs">
<DialogTitle sx={{ textAlign: "center" }}>Choisissez une méthode de partage</DialogTitle>
<DialogActions sx={{ display: "flex", justifyContent: "center", gap: 2 }}>
<Button onClick={handleShareByEmail}>Partager par email</Button>
<Button onClick={handleShareByUrl}>Partager par URL</Button>
</DialogActions>
</Dialog>
</>
);
};
export default ShareQuizModal;

View file

@ -28,7 +28,7 @@ import {
NativeSelect,
CardContent,
styled,
DialogContentText
DialogContentText,
} from '@mui/material';
import {
Search,
@ -39,8 +39,8 @@ import {
FolderCopy,
ContentCopy,
Edit,
Share,
} from '@mui/icons-material';
import ShareQuizModal from 'src/components/ShareQuizModal/ShareQuizModal';
// Create a custom-styled Card component
const CustomCard = styled(Card)({
@ -104,7 +104,7 @@ const Dashboard: React.FC = () => {
fetchData();
}, []);
useEffect(() => {
if (rooms.length > 0 && !selectedRoom) {
selectRoom(rooms[rooms.length - 1]);
@ -120,41 +120,41 @@ const Dashboard: React.FC = () => {
}
};
// Créer une salle
const createRoom = async (title: string) => {
// Créer la salle et récupérer l'objet complet
const newRoom = await ApiService.createRoom(title);
// Mettre à jour la liste des salles
const updatedRooms = await ApiService.getUserRooms();
setRooms(updatedRooms as RoomType[]);
// Sélectionner la nouvelle salle avec son ID
selectRoomByName(newRoom); // Utiliser l'ID de l'objet retourné
};
// Créer une salle
const createRoom = async (title: string) => {
// Créer la salle et récupérer l'objet complet
const newRoom = await ApiService.createRoom(title);
// Mettre à jour la liste des salles
const updatedRooms = await ApiService.getUserRooms();
setRooms(updatedRooms as RoomType[]);
// Sélectionner la nouvelle salle avec son ID
selectRoomByName(newRoom); // Utiliser l'ID de l'objet retourné
};
// Sélectionner une salle
const selectRoomByName = (roomId: string) => {
const room = rooms.find(r => r._id === roomId);
selectRoom(room);
localStorage.setItem('selectedRoomId', roomId);
};
// Sélectionner une salle
const selectRoomByName = (roomId: string) => {
const room = rooms.find(r => r._id === roomId);
selectRoom(room);
localStorage.setItem('selectedRoomId', roomId);
};
const handleCreateRoom = async () => {
if (newRoomTitle.trim()) {
try {
const handleCreateRoom = async () => {
if (newRoomTitle.trim()) {
try {
await createRoom(newRoomTitle);
const userRooms = await ApiService.getUserRooms();
setRooms(userRooms as RoomType[]);
setOpenAddRoomDialog(false);
setNewRoomTitle('');
} catch (error) {
setErrorMessage(error instanceof Error ? error.message : "Erreur inconnue");
setShowErrorDialog(true);
}
}
};
setOpenAddRoomDialog(false);
setNewRoomTitle('');
} catch (error) {
setErrorMessage(error instanceof Error ? error.message : "Erreur inconnue");
setShowErrorDialog(true);
}
}
};
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
setSelectedFolderId(event.target.value);
@ -397,9 +397,21 @@ const Dashboard: React.FC = () => {
} else {
const randomSixDigit = Math.floor(100000 + Math.random() * 900000);
navigate(`/teacher/manage-room/${quiz._id}/${randomSixDigit}`);
}
}
};
const handleShareByUrl = (quiz: QuizType) => {
const quizUrl = `${window.location.origin}/teacher/share/${quiz._id}`;
navigator.clipboard.writeText(quizUrl)
.then(() => {
window.alert('URL a été copiée avec succès.');
})
.catch(() => {
window.alert('Une erreur est survenue lors de la copie de l\'URL.');
});
};
return (
<div className="dashboard">
<div className="title">Tableau de bord</div>
@ -497,41 +509,41 @@ const Dashboard: React.FC = () => {
<Tooltip title="Renommer dossier" placement="top">
<div>
<IconButton
color="primary"
onClick={handleRenameFolder}
disabled={selectedFolderId == ''} // cannot action on all
>
{' '}
<Edit />{' '}
</IconButton>
<IconButton
color="primary"
onClick={handleRenameFolder}
disabled={selectedFolderId == ''} // cannot action on all
>
{' '}
<Edit />{' '}
</IconButton>
</div>
</Tooltip>
<Tooltip title="Dupliquer dossier" placement="top">
<div>
<IconButton
color="primary"
onClick={handleDuplicateFolder}
disabled={selectedFolderId == ''} // cannot action on all
>
{' '}
<FolderCopy />{' '}
</IconButton>
<IconButton
color="primary"
onClick={handleDuplicateFolder}
disabled={selectedFolderId == ''} // cannot action on all
>
{' '}
<FolderCopy />{' '}
</IconButton>
</div>
</Tooltip>
<Tooltip title="Supprimer dossier" placement="top">
<div>
<IconButton
aria-label="delete"
color="primary"
onClick={handleDeleteFolder}
disabled={selectedFolderId == ''} // cannot action on all
>
{' '}
<DeleteOutline />{' '}
</IconButton>
<IconButton
aria-label="delete"
color="primary"
onClick={handleDeleteFolder}
disabled={selectedFolderId == ''} // cannot action on all
>
{' '}
<DeleteOutline />{' '}
</IconButton>
</div>
</Tooltip>
</div>
@ -571,9 +583,8 @@ const Dashboard: React.FC = () => {
onClick={() => handleLancerQuiz(quiz)}
disabled={!validateQuiz(quiz.content)}
>
{`${quiz.title} (${quiz.content.length} question${
quiz.content.length > 1 ? 's' : ''
})`}
{`${quiz.title} (${quiz.content.length} question${quiz.content.length > 1 ? 's' : ''
})`}
</Button>
</div>
</Tooltip>
@ -621,9 +632,15 @@ const Dashboard: React.FC = () => {
</IconButton>
</Tooltip>
<div className="quiz-share">
<ShareQuizModal quiz={quiz} />
</div>
<Tooltip title="Partager par URL" placement="top">
<IconButton
aria-label="partarger quiz"
color="primary"
onClick={() => handleShareByUrl(quiz)}
>
<Share />
</IconButton>
</Tooltip>
</div>
</div>
))}

View file

@ -836,36 +836,6 @@ public async login(email: string, password: string): Promise<any> {
}
}
async ShareQuiz(quizId: string, email: string): Promise<ApiResponse> {
try {
if (!quizId || !email) {
throw new Error(`quizId and email are required.`);
}
const url: string = this.constructRequestUrl(`/quiz/Share`);
const headers = this.constructRequestHeaders();
const body = { quizId, email };
const result: AxiosResponse = await axios.put(url, body, { headers: headers });
if (result.status !== 200) {
throw new Error(`Update and share quiz failed. Status: ${result.status}`);
}
return true;
} catch (error) {
console.log("Error details: ", error);
if (axios.isAxiosError(error)) {
const err = error as AxiosError;
const data = err.response?.data as { error: string } | undefined;
return data?.error || 'Unknown server error during request.';
}
return `An unexpected error occurred.`;
}
}
async getSharedQuiz(quizId: string): Promise<string> {
try {
if (!quizId) {