mirror of
https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir.git
synced 2025-08-11 21:23:54 -04:00
new changes with tests
This commit is contained in:
parent
0d7b6ee5eb
commit
46c17ba127
4 changed files with 261 additions and 178 deletions
|
|
@ -1,74 +1,81 @@
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { render, fireEvent, screen, waitFor } from '@testing-library/react';
|
import { render, screen, fireEvent, act } from '@testing-library/react';
|
||||||
import '@testing-library/jest-dom';
|
import ShareQuizModal from '../../../components/ShareQuizModal/ShareQuizModal.tsx';
|
||||||
import ShareQuizModal from '../../../components/ShareQuizModal/ShareQuizModal';
|
|
||||||
import { QuizType } from '../../../Types/QuizType';
|
import { QuizType } from '../../../Types/QuizType';
|
||||||
import ApiService from '../../../services/ApiService';
|
import '@testing-library/jest-dom';
|
||||||
|
|
||||||
jest.mock('../../../services/ApiService');
|
|
||||||
|
|
||||||
Object.assign(navigator, {
|
|
||||||
clipboard: {
|
|
||||||
writeText: jest.fn().mockResolvedValue(undefined),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
window.alert = jest.fn();
|
|
||||||
|
|
||||||
|
describe('ShareQuizModal', () => {
|
||||||
const mockQuiz: QuizType = {
|
const mockQuiz: QuizType = {
|
||||||
_id: '1',
|
_id: '123',
|
||||||
title: 'Sample Quiz',
|
folderId: 'folder-123',
|
||||||
content: ['::Question 1:: What is 2+2? {=4 ~3 ~5}'],
|
folderName: 'Test Folder',
|
||||||
folderId: 'folder1',
|
userId: 'user-123',
|
||||||
folderName: 'Sample Folder',
|
title: 'Test Quiz',
|
||||||
userId: 'user1',
|
content: ['Question 1', 'Question 2'],
|
||||||
created_at: new Date(),
|
created_at: new Date(),
|
||||||
updated_at: new Date(),
|
updated_at: new Date(),
|
||||||
};
|
};
|
||||||
|
|
||||||
describe('ShareQuizModal', () => {
|
beforeAll(() => {
|
||||||
|
// Properly mock the clipboard API
|
||||||
|
Object.defineProperty(navigator, 'clipboard', {
|
||||||
|
value: {
|
||||||
|
writeText: jest.fn().mockImplementation(() => Promise.resolve()),
|
||||||
|
},
|
||||||
|
writable: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
beforeEach(() => {
|
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should call ApiService.ShareQuiz when sharing by email', async () => {
|
it('renders the share button', () => {
|
||||||
render(<ShareQuizModal quiz={mockQuiz} />);
|
render(<ShareQuizModal quiz={mockQuiz} />);
|
||||||
|
expect(screen.getByLabelText('partager quiz')).toBeInTheDocument();
|
||||||
const shareButton = screen.getByRole('button', { name: /partager quiz/i });
|
expect(screen.getByTestId('ShareIcon')).toBeInTheDocument();
|
||||||
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 () => {
|
it('copies the quiz URL to clipboard when share button is clicked', async () => {
|
||||||
render(<ShareQuizModal quiz={mockQuiz} />);
|
render(<ShareQuizModal quiz={mockQuiz} />);
|
||||||
|
const shareButton = screen.getByLabelText('partager quiz');
|
||||||
|
|
||||||
// Open the modal
|
await act(async () => {
|
||||||
const shareButton = screen.getByRole('button', { name: /partager quiz/i });
|
|
||||||
fireEvent.click(shareButton);
|
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.');
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
|
||||||
|
`${window.location.origin}/teacher/share/${mockQuiz._id}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// Check for feedback dialog content
|
||||||
|
expect(screen.getByText(/L'URL de partage pour le quiz/i)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(mockQuiz.title)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/a été copiée\./i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows error message when clipboard write fails', async () => {
|
||||||
|
// Override the mock to reject
|
||||||
|
(navigator.clipboard.writeText as jest.Mock).mockRejectedValueOnce(new Error('Clipboard write failed'));
|
||||||
|
|
||||||
|
render(<ShareQuizModal quiz={mockQuiz} />);
|
||||||
|
const shareButton = screen.getByLabelText('partager quiz');
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(shareButton);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.getByText(/Une erreur est survenue lors de la copie de l'URL\./i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('displays the quiz title in the success message', async () => {
|
||||||
|
render(<ShareQuizModal quiz={mockQuiz} />);
|
||||||
|
const shareButton = screen.getByLabelText('partager quiz');
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(shareButton);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.getByText(mockQuiz.title)).toBeInTheDocument();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
@ -1,67 +1,90 @@
|
||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { Dialog, DialogTitle, DialogActions, Button, Tooltip, IconButton } from '@mui/material';
|
import { Dialog, DialogTitle, DialogActions, Button, Tooltip, IconButton, Typography, Box } from '@mui/material';
|
||||||
import { Share } from '@mui/icons-material';
|
import { Share } from '@mui/icons-material';
|
||||||
import { QuizType } from '../../Types/QuizType';
|
import { QuizType } from '../../Types/QuizType';
|
||||||
import ApiService from '../../services/ApiService';
|
|
||||||
|
|
||||||
interface ShareQuizModalProps {
|
interface ShareQuizModalProps {
|
||||||
quiz: QuizType;
|
quiz: QuizType;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ShareQuizModal: React.FC<ShareQuizModalProps> = ({ quiz }) => {
|
const ShareQuizModal: React.FC<ShareQuizModalProps> = ({ quiz }) => {
|
||||||
const [open, setOpen] = useState(false);
|
const [_open, setOpen] = useState(false);
|
||||||
|
const [feedback, setFeedback] = useState({
|
||||||
const handleOpenModal = () => setOpen(true);
|
open: false,
|
||||||
|
title: '',
|
||||||
|
isError: false
|
||||||
|
});
|
||||||
|
|
||||||
const handleCloseModal = () => setOpen(false);
|
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 handleShareByUrl = () => {
|
||||||
const quizUrl = `${window.location.origin}/teacher/share/${quiz._id}`;
|
const quizUrl = `${window.location.origin}/teacher/share/${quiz._id}`;
|
||||||
navigator.clipboard.writeText(quizUrl)
|
navigator.clipboard.writeText(quizUrl)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
window.alert('URL a été copiée avec succès.');
|
setFeedback({
|
||||||
|
open: true,
|
||||||
|
title: 'L\'URL de partage pour le quiz',
|
||||||
|
isError: false
|
||||||
|
});
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
window.alert('Une erreur est survenue lors de la copie de l\'URL.');
|
setFeedback({
|
||||||
|
open: true,
|
||||||
|
title: 'Une erreur est survenue lors de la copie de l\'URL.',
|
||||||
|
isError: true
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
handleCloseModal();
|
handleCloseModal();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const closeFeedback = () => {
|
||||||
|
setFeedback(prev => ({ ...prev, open: false }));
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Tooltip title="Partager quiz" placement="top">
|
<Tooltip title="Partager" placement="top">
|
||||||
<IconButton color="primary" onClick={handleOpenModal} aria-label="partager quiz">
|
<IconButton color="primary" onClick={handleShareByUrl} aria-label="partager quiz">
|
||||||
<Share />
|
<Share />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Dialog open={open} onClose={handleCloseModal} fullWidth maxWidth="xs">
|
{/* Feedback Dialog */}
|
||||||
<DialogTitle sx={{ textAlign: "center" }}>Choisissez une méthode de partage</DialogTitle>
|
<Dialog
|
||||||
<DialogActions sx={{ display: "flex", justifyContent: "center", gap: 2 }}>
|
open={feedback.open}
|
||||||
<Button onClick={handleShareByEmail}>Partager par email</Button>
|
onClose={closeFeedback}
|
||||||
<Button onClick={handleShareByUrl}>Partager par URL</Button>
|
fullWidth
|
||||||
|
maxWidth="xs"
|
||||||
|
>
|
||||||
|
<DialogTitle sx={{ textAlign: "center" }}>
|
||||||
|
<Box>
|
||||||
|
{feedback.isError ? (
|
||||||
|
<Typography color="error.main">
|
||||||
|
{feedback.title}
|
||||||
|
</Typography>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Typography component="span">
|
||||||
|
L'URL de partage pour le quiz{' '}
|
||||||
|
</Typography>
|
||||||
|
<Typography component="span" fontWeight="bold">
|
||||||
|
{quiz.title}
|
||||||
|
</Typography>
|
||||||
|
<Typography component="span">
|
||||||
|
{' '}a été copiée.
|
||||||
|
</Typography>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogActions sx={{ display: "flex", justifyContent: "center" }}>
|
||||||
|
<Button
|
||||||
|
onClick={closeFeedback}
|
||||||
|
variant="contained"
|
||||||
|
>
|
||||||
|
OK
|
||||||
|
</Button>
|
||||||
</DialogActions>
|
</DialogActions>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</>
|
</>
|
||||||
|
|
|
||||||
|
|
@ -564,7 +564,7 @@ const Dashboard: React.FC = () => {
|
||||||
{quizzesByFolder[folderName].map((quiz: QuizType) => (
|
{quizzesByFolder[folderName].map((quiz: QuizType) => (
|
||||||
<div className="quiz" key={quiz._id}>
|
<div className="quiz" key={quiz._id}>
|
||||||
<div className="title">
|
<div className="title">
|
||||||
<Tooltip title="Lancer quiz" placement="top">
|
<Tooltip title="Démarrer" placement="top">
|
||||||
<div>
|
<div>
|
||||||
<Button
|
<Button
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
|
|
@ -580,7 +580,7 @@ const Dashboard: React.FC = () => {
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="actions">
|
<div className="actions">
|
||||||
<Tooltip title="Télécharger quiz" placement="top">
|
<Tooltip title="Télécharger" placement="top">
|
||||||
<IconButton
|
<IconButton
|
||||||
color="primary"
|
color="primary"
|
||||||
onClick={() => downloadTxtFile(quiz)}
|
onClick={() => downloadTxtFile(quiz)}
|
||||||
|
|
@ -590,7 +590,7 @@ const Dashboard: React.FC = () => {
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip title="Modifier quiz" placement="top">
|
<Tooltip title="Modifier" placement="top">
|
||||||
<IconButton
|
<IconButton
|
||||||
color="primary"
|
color="primary"
|
||||||
onClick={() => handleEditQuiz(quiz)}
|
onClick={() => handleEditQuiz(quiz)}
|
||||||
|
|
@ -600,7 +600,7 @@ const Dashboard: React.FC = () => {
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip title="Dupliquer quiz" placement="top">
|
<Tooltip title="Dupliquer" placement="top">
|
||||||
<IconButton
|
<IconButton
|
||||||
color="primary"
|
color="primary"
|
||||||
onClick={() => handleDuplicateQuiz(quiz)}
|
onClick={() => handleDuplicateQuiz(quiz)}
|
||||||
|
|
@ -610,7 +610,7 @@ const Dashboard: React.FC = () => {
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip title="Supprimer quiz" placement="top">
|
<Tooltip title="Supprimer" placement="top">
|
||||||
<IconButton
|
<IconButton
|
||||||
aria-label="delete"
|
aria-label="delete"
|
||||||
color="primary"
|
color="primary"
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import React, { useState, useEffect } from 'react';
|
||||||
import { useParams, useNavigate } from 'react-router-dom';
|
import { useParams, useNavigate } from 'react-router-dom';
|
||||||
import { FolderType } from '../../../Types/FolderType';
|
import { FolderType } from '../../../Types/FolderType';
|
||||||
import './share.css';
|
import './share.css';
|
||||||
import { Button, NativeSelect } from '@mui/material';
|
import { Button, NativeSelect, Typography, Box, Divider } from '@mui/material';
|
||||||
import ReturnButton from 'src/components/ReturnButton/ReturnButton';
|
import ReturnButton from 'src/components/ReturnButton/ReturnButton';
|
||||||
import ApiService from '../../../services/ApiService';
|
import ApiService from '../../../services/ApiService';
|
||||||
|
|
||||||
|
|
@ -12,11 +12,13 @@ const Share: React.FC = () => {
|
||||||
|
|
||||||
const [quizTitle, setQuizTitle] = useState('');
|
const [quizTitle, setQuizTitle] = useState('');
|
||||||
const [selectedFolder, setSelectedFolder] = useState<string>('');
|
const [selectedFolder, setSelectedFolder] = useState<string>('');
|
||||||
|
|
||||||
const [folders, setFolders] = useState<FolderType[]>([]);
|
const [folders, setFolders] = useState<FolderType[]>([]);
|
||||||
|
const [quizExists, setQuizExists] = useState(false);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
|
try {
|
||||||
if (!id) {
|
if (!id) {
|
||||||
window.alert(`Une erreur est survenue.\n Le quiz n'a pas été trouvé\nVeuillez réessayer plus tard`)
|
window.alert(`Une erreur est survenue.\n Le quiz n'a pas été trouvé\nVeuillez réessayer plus tard`)
|
||||||
console.error('Quiz not found for id:', id);
|
console.error('Quiz not found for id:', id);
|
||||||
|
|
@ -33,8 +35,8 @@ const Share: React.FC = () => {
|
||||||
const quizIds = await ApiService.getAllQuizIds();
|
const quizIds = await ApiService.getAllQuizIds();
|
||||||
|
|
||||||
if (quizIds.includes(id)) {
|
if (quizIds.includes(id)) {
|
||||||
window.alert(`Le quiz que vous essayez d'importer existe déjà sur votre compte.`)
|
setQuizExists(true);
|
||||||
navigate('/teacher/dashboard');
|
setLoading(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -58,10 +60,16 @@ const Share: React.FC = () => {
|
||||||
}
|
}
|
||||||
|
|
||||||
setQuizTitle(title);
|
setQuizTitle(title);
|
||||||
|
setLoading(false);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching data:', error);
|
||||||
|
setLoading(false);
|
||||||
|
navigate('/teacher/dashboard');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
fetchData();
|
fetchData();
|
||||||
}, []);
|
}, [id, navigate]);
|
||||||
|
|
||||||
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
||||||
setSelectedFolder(event.target.value);
|
setSelectedFolder(event.target.value);
|
||||||
|
|
@ -69,7 +77,6 @@ const Share: React.FC = () => {
|
||||||
|
|
||||||
const handleQuizSave = async () => {
|
const handleQuizSave = async () => {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
if (selectedFolder == '') {
|
if (selectedFolder == '') {
|
||||||
alert("Veuillez choisir un dossier");
|
alert("Veuillez choisir un dossier");
|
||||||
return;
|
return;
|
||||||
|
|
@ -91,6 +98,52 @@ const Share: React.FC = () => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <div className='quizImport'>Chargement...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (quizExists) {
|
||||||
|
return (
|
||||||
|
<div className='quizImport'>
|
||||||
|
<div className='importHeader'>
|
||||||
|
<ReturnButton />
|
||||||
|
<div className='titleContainer'>
|
||||||
|
<div className='mainTitle'>Quiz déjà existant</div>
|
||||||
|
</div>
|
||||||
|
<div className='dumb'></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className='editSection'>
|
||||||
|
<Box sx={{
|
||||||
|
textAlign: 'center',
|
||||||
|
padding: 3,
|
||||||
|
maxWidth: 600,
|
||||||
|
margin: '0 auto'
|
||||||
|
}}>
|
||||||
|
<Typography variant="h6" gutterBottom>
|
||||||
|
Le quiz que vous essayez d'importer existe déjà sur votre compte.
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
onClick={() => navigate('/teacher/dashboard')}
|
||||||
|
sx={{ mt: 3, mb: 1 }}
|
||||||
|
fullWidth
|
||||||
|
>
|
||||||
|
Retour au tableau de bord
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
Si vous souhaitiez créer une copie de ce quiz,
|
||||||
|
vous pouvez utiliser la fonction "Dupliquer" disponible
|
||||||
|
dans votre tableau de bord.
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='quizImport'>
|
<div className='quizImport'>
|
||||||
<div className='importHeader'>
|
<div className='importHeader'>
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue