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, NativeSelect,
CardContent, CardContent,
styled, styled,
DialogContentText DialogContentText,
} from '@mui/material'; } from '@mui/material';
import { import {
Search, Search,
@ -39,8 +39,8 @@ import {
FolderCopy, FolderCopy,
ContentCopy, ContentCopy,
Edit, Edit,
Share,
} from '@mui/icons-material'; } from '@mui/icons-material';
import ShareQuizModal from 'src/components/ShareQuizModal/ShareQuizModal';
// Create a custom-styled Card component // Create a custom-styled Card component
const CustomCard = styled(Card)({ const CustomCard = styled(Card)({
@ -400,6 +400,18 @@ const Dashboard: React.FC = () => {
} }
}; };
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 ( return (
<div className="dashboard"> <div className="dashboard">
<div className="title">Tableau de bord</div> <div className="title">Tableau de bord</div>
@ -571,8 +583,7 @@ const Dashboard: React.FC = () => {
onClick={() => handleLancerQuiz(quiz)} onClick={() => handleLancerQuiz(quiz)}
disabled={!validateQuiz(quiz.content)} disabled={!validateQuiz(quiz.content)}
> >
{`${quiz.title} (${quiz.content.length} question${ {`${quiz.title} (${quiz.content.length} question${quiz.content.length > 1 ? 's' : ''
quiz.content.length > 1 ? 's' : ''
})`} })`}
</Button> </Button>
</div> </div>
@ -621,9 +632,15 @@ const Dashboard: React.FC = () => {
</IconButton> </IconButton>
</Tooltip> </Tooltip>
<div className="quiz-share"> <Tooltip title="Partager par URL" placement="top">
<ShareQuizModal quiz={quiz} /> <IconButton
</div> aria-label="partarger quiz"
color="primary"
onClick={() => handleShareByUrl(quiz)}
>
<Share />
</IconButton>
</Tooltip>
</div> </div>
</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> { async getSharedQuiz(quizId: string): Promise<string> {
try { try {
if (!quizId) { if (!quizId) {