Skip to content

Commit

Permalink
Closes #4 Added 10 QuizTimer to all quizzes
Browse files Browse the repository at this point in the history
Signed-off-by: Akash <akashsingh2210670@gmail.com>
  • Loading branch information
SkySingh04 committed May 4, 2024
1 parent 65205b8 commit b9c55f6
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 11 deletions.
35 changes: 24 additions & 11 deletions app/[quizid]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ type QuizQuestion = {

function Quiz() {

const quizTime = 600000; // This can be updated to allow for custom quiz times


const router = useRouter();
const SearchParams = useSearchParams();
const quizId : any = SearchParams.get('id')
Expand All @@ -35,6 +35,7 @@ function Quiz() {
const [score, setScore] = useState(0);
const [isFinalQuestion, setIsFinalQuestion] = useState(false);
const [isTimeUp, setIsTimeUp] = useState(false);
const [timeLeft, setTimeLeft] = useState(quizTime/1000); // Time limit in seconds


async function fetchQuizData() {
Expand All @@ -59,20 +60,28 @@ function Quiz() {

}

useEffect(() => {
const timer = setTimeout(() => {
setIsTimeUp(true);
}, 3000); // Set the quiz time limit here. 60000ms = 1 minute

// Clear the timer when the component unmounts
return () => clearTimeout(timer);
}, []);
// Update the useEffect hook where the timer is set
useEffect(() => {
const timer = setTimeout(() => {
setIsTimeUp(true);
}, quizTime);

const interval = setInterval(() => {
setTimeLeft((prevTimeLeft) => prevTimeLeft - 1);
}, 1000); // Decrease timeLeft by 1 every second

// Clear the timer and the interval when the component unmounts or when the time is up
return () => {
clearTimeout(timer);
clearInterval(interval);
};
}, []);

useEffect(() => {
if (isTimeUp) {
console.log('Time is up!');
toast.error('Time is up! Auto Submitting Quiz');
// handleQuizSubmit();
handleQuizSubmit();
}
}, [isTimeUp]);

Expand Down Expand Up @@ -138,7 +147,7 @@ function Quiz() {

//check if all questions are attempted

if (selectedOptions.length !== correctAnswers.length){
if (selectedOptions.length !== correctAnswers.length && !isTimeUp){
toast.error("Please attempt all of the questions")
return
}
Expand Down Expand Up @@ -188,6 +197,7 @@ function Quiz() {

return (
<div className="min-h-screen flex items-center justify-center">

{currentQuestion ? (
<div className="bg-slate-800 text-white p-8 rounded-lg shadow-lg w-4/6 h-4/6">
<h2 className="text-xl mb-4">Question {currentQuestionIndex + 1}:</h2>
Expand Down Expand Up @@ -216,6 +226,9 @@ function Quiz() {
Previous
</button>
)}
<div className=" bg-slate-600 text-white p-2 rounded-lg shadow-lg">
Time left: {timeLeft} seconds
</div>
{isFinalQuestion ? (
<button
className="px-4 py-2 bg-blue-500 hover-bg-blue-700 text-white rounded-md"
Expand Down
73 changes: 73 additions & 0 deletions app/studentdata/page.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// import { renderHook, act } from '@testing-library/react-hooks';
// import { useRouter } from 'next/router';
// import { auth, db, updateDoc, arrayUnion } from 'firebase/firestore';
// import toast from 'react-hot-toast';
// import { formatDateTime } from '../Date';
// import { Quiz } from '../[quizid]/page';

// jest.mock('react', () => ({
// ...jest.requireActual('react'),
// useState: jest.fn(),
// useEffect: jest.fn(),
// }));

// jest.mock('next/router', () => ({
// useRouter: jest.fn(),
// }));

// jest.mock('firebase/firestore', () => ({
// auth: { currentUser: { uid: 'testUid' } },
// db: jest.fn(),
// updateDoc: jest.fn(),
// arrayUnion: jest.fn(),
// }));

// jest.mock('react-hot-toast', () => ({
// success: jest.fn(),
// }));

// jest.mock('../Date', () => ({
// formatDateTime: jest.fn(),
// }));

// describe('Quiz', () => {
// it('handleQuizSubmit', async () => {
// const useStateMock = (initState: any) => [initState, jest.fn()];
// (useRouter as jest.Mock).mockReturnValue({ push: jest.fn() });
// (formatDateTime as jest.Mock).mockReturnValue('testDateTime');
// (useState as jest.Mock)
// .mockImplementationOnce(() => useStateMock([{ question: 'testQuestion', correctAnswer: 'testAnswer' }])) // questions
// .mockImplementationOnce(() => useStateMock(['testAnswer'])) // selectedOptions
// .mockImplementationOnce(() => useStateMock('testQuizId')) // quizId
// .mockImplementationOnce(() => useStateMock('testQuizName')) // quizName
// .mockImplementationOnce(() => useStateMock('testCourse')) // course
// .mockImplementationOnce(() => useStateMock('testCourseCode')); // courseCode

// const { result } = renderHook(() => Quiz());
// await act(async () => {
// await result.current.handleQuizSubmit();
// });

// expect(updateDoc).toHaveBeenCalledWith(
// { __collection__: 'users', id: 'testUid' },
// {
// quizData: [
// {
// score: 1,
// totalQuestions: 1,
// selectedOptions: ['testAnswer'],
// correctAnswers: ['testAnswer'],
// fetchedQuestions: [{ question: 'testQuestion', correctAnswer: 'testAnswer' }],
// quizId: 'testQuizId',
// quizName: 'testQuizName',
// course: 'testCourse',
// courseCode: 'testCourseCode',
// time: 'testDateTime',
// },
// ],
// }
// );
// expect(useRouter().push).toHaveBeenCalledWith('/results');
// expect(toast.success).toHaveBeenCalledWith('Quiz Submitted Succesfully!');
// });
// });

0 comments on commit b9c55f6

Please sign in to comment.