Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added 2 new unit tests for inputfield, and signout #30

Merged
merged 2 commits into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 42 additions & 1 deletion src/__test__/component/app.test.jsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import Calendar from '../../component/calendarComponent/calendar';
import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react';
import { render, screen, fireEvent,waitFor } from '@testing-library/react';
import { render, screen, fireEvent,waitFor, findByText } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import App from '../../App';
import { async } from 'q';

jest.mock('@supabase/auth-helpers-react', () => ({
useSession: jest.fn(),
useSupabaseClient: jest.fn(),
}));
describe('Testing UI with login and navigation', () => {
afterEach(() => {
jest.clearAllMocks(); // Clear all mocked implementations after each test
});

test('renders the correct page after sign in', () => {
// Set up the mock implementations
useSession.mockImplementation(() => ({
Expand Down Expand Up @@ -84,4 +89,40 @@ describe('Testing UI with login and navigation', () => {
const pageElement = getByText('What would you like to do first?');
expect(pageElement).toBeInTheDocument();
});

test('testing that the sign out button signs you out and shows sign in screen', async () => {
// Set up the mock implementations
useSession.mockImplementation(() => ({
user: { email: '[email protected]' },
provider_token: 'mock_provider_token',
}));
useSupabaseClient.mockImplementation(() => ({
auth: {
signInWithOAuth: jest.fn(),
signOut: jest.fn(),
},
}));

const { getByText, findByText, rerender } = render(
<MemoryRouter initialEntries={['/home']}>
<App />
</MemoryRouter>
);

const signOutButton = getByText('Sign Out');
fireEvent.click(signOutButton);

// Mock the useSession hook to return null and force a re-render of the App component
useSession.mockImplementation(() => null);
rerender(
<MemoryRouter initialEntries={['/home']}>
<App />
</MemoryRouter>
);

const signInButton = await waitFor(() => findByText('Sign In With Google'));
expect(signInButton).toBeInTheDocument();
});


});
185 changes: 185 additions & 0 deletions src/__test__/component/calendar-int.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import React, { useState } from 'react';
import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react';
import { render, screen, fireEvent,waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import App from '../../App';
import { act } from 'react-dom/test-utils';
import {deleteEvent} from '../../component/calendarComponent/calendar';
jest.mock('@supabase/auth-helpers-react', () => ({
useSession: jest.fn(),
useSupabaseClient: jest.fn(),
}));

describe('Testing UI with login and navigation', () => {
const mocking_response = {
"kind": "calendar#event",
"id": "mock_provider_token", // Replace with a mock string
"status": "confirmed", // Replace with a mock string
"summary" : "Meeting",
"description": "Serious", // Replace with a mock string
"start": {
"dateTime": "2023-12-15T10:00:00-08:00", // Replace with a mock datetime
"timeZone": "America/Los_Angeles"
},
"end": {
"dateTime": "2023-12-15T11:00:00-08:00", // Replace with a mock datetime
"timeZone": "America/Los_Angeles"
},
};

beforeEach(() => {
global.fetch = jest.fn(() =>
Promise.resolve({
ok: true,
json: () => Promise.resolve(mocking_response)
})
);
jest.useFakeTimers();
fetch.mockClear();
});

afterEach(() => {
jest.runOnlyPendingTimers();
jest.useRealTimers();
jest.restoreAllMocks();
});


test('testing proper addition of event', async () => {
// Mock window.alert
window.alert = jest.fn();

// Set up the mock implementations
useSession.mockImplementation(() => ({
user: { email: '[email protected]' },
provider_token: 'mock_provider_token',
}));
useSupabaseClient.mockImplementation(() => ({
auth: {
signInWithOAuth: jest.fn(),
signOut: jest.fn(),
},
}));

// Render the component
const { getByText, getByPlaceholderText } = render(
<MemoryRouter initialEntries={['/home']}>
<App />
</MemoryRouter>
);
await act(async () => {
fireEvent.change(getByPlaceholderText('date'), { target: { value: '2023-12-15' } });
fireEvent.change(getByPlaceholderText('start time'), { target: { value: '10:00' } });
fireEvent.change(getByPlaceholderText('end time'), { target: { value: '11:00' } });
fireEvent.change(getByPlaceholderText('Event Name'), { target: { value: "Meeting" } });
fireEvent.change(getByPlaceholderText('Event Description'), { target: { value: "Serious" } });

// Simulate submitting the form or clicking the 'Add' button
fireEvent.click(getByText('Add'));
});
// Wait for the fetch to be called and assert it was called correctly
await waitFor(() => {
expect(fetch).toHaveBeenCalledWith(
"https://www.googleapis.com/calendar/v3/calendars/primary/events",
expect.objectContaining({
method: 'POST',
headers: expect.objectContaining({
'Authorization': 'Bearer mock_provider_token', // This matches the Authorization format in your fetch call
}),
body: expect.any(String), // This checks that body is a string, but does not specify the content
})
);
});
await act(async () => {
fireEvent.click(getByText('16'));
});

await waitFor(() => {
expect(mocking_response.summary).toBe('Meeting');
});
});
test('testing API call on day click', async () => {
// Set up the mock implementations
useSession.mockImplementation(() => ({
user: { email: '[email protected]' },
provider_token: 'mock_provider_token',
}));
useSupabaseClient.mockImplementation(() => ({
auth: {
signInWithOAuth: jest.fn(),
signOut: jest.fn(),
},
}));

// Render the component
const { getByText } = render(
<MemoryRouter initialEntries={['/home']}>
<App />
</MemoryRouter>
);

// Simulate clicking on a day
await act(async () => {
fireEvent.click(getByText('15'));
});

// Wait for the fetch to be called and assert it was called correctly
// Wait for the fetch to be called and assert it was called correctly
await waitFor(() => {
expect(fetch).toHaveBeenCalledWith(
expect.stringMatching(/^https:\/\/www.googleapis.com\/calendar\/v3\/calendars\/primary\/events\?timeMin=.*&timeMax=.*/),
expect.objectContaining({
method: 'GET',
headers: expect.objectContaining({
'Authorization': 'Bearer mock_provider_token',
}),
})
);
});
});
test('testing API call on event delete', async () => {
// Set up the mock implementations
useSession.mockImplementation(() => ({
user: { email: '[email protected]' },
provider_token: 'mock_provider_token',
}));
useSupabaseClient.mockImplementation(() => ({
auth: {
signInWithOAuth: jest.fn(),
signOut: jest.fn(),
},
}));

// Mock the fetch function to return the mock response when getting events
global.fetch = jest.fn((url, options) => {
if (options.method === 'GET') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve([mocking_response]),
});
} else if (options.method === 'DELETE') {
return Promise.resolve({
status: 204,
json: () => Promise.resolve({ message: 'Event deleted' }), // Add a default response body
});
}
});

// Call deleteEvent directly
await deleteEvent('mock_event_id', 'mock_provider_token'); // Replace with the actual event ID

// Wait for the fetch to be called and assert it was called correctly
await waitFor(() => {
expect(fetch).toHaveBeenCalledWith(
expect.stringMatching(/^https:\/\/www.googleapis.com\/calendar\/v3\/calendars\/primary\/events\/.*$/),
expect.objectContaining({
method: 'DELETE',
headers: expect.objectContaining({
'Authorization': 'Bearer mock_provider_token',
}),
})
);
});
});

});
21 changes: 19 additions & 2 deletions src/__test__/component/calendar.test.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import Calendar from '../../component/calendarComponent/calendar';
import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react';
import { render, screen, fireEvent,waitFor } from '@testing-library/react';
import InputField from '../../component/calendarComponent/input_field';

import { MemoryRouter } from 'react-router-dom';
jest.mock('@supabase/auth-helpers-react', () => ({
useSession: jest.fn(),
Expand All @@ -20,7 +22,7 @@ describe('Calendar component tests', () => {


expect(monthYearElement).toBeInTheDocument();

});
test('renders event modal when a day is clicked', () => {
useSession.mockImplementation(() => ({
Expand All @@ -40,4 +42,19 @@ describe('Calendar component tests', () => {
});


});
});

test('cancel creation of a new event to calendar', async () => {
const { getByPlaceholderText, getByText } = render(<InputField />);
const eventName = getByPlaceholderText('Event Name');
const eventDescription = getByPlaceholderText('Event Description');

fireEvent.change(eventName, { target: { value: 'Meeting' } });
fireEvent.change(eventDescription, { target: { value: 'Serious' } });

fireEvent.click(getByText('Cancel'));

expect(eventName.value).toBe('');
expect(eventDescription.value).toBe('');

});
31 changes: 16 additions & 15 deletions src/component/calendarComponent/calendar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@ import React, { useState} from 'react';
import { useSession} from '@supabase/auth-helpers-react';
import EventModal from './eventModal'
import './calendar.css'
export async function deleteEvent(eventId, provider_token) {
const response = await fetch(`https://www.googleapis.com/calendar/v3/calendars/primary/events/${eventId}`, {
method: "DELETE",
headers: {
'Authorization': 'Bearer ' + provider_token, // Access token for Google
},
});

if (!response||(response.status !== 204 && !response.ok)) {
throw new Error(`Failed to delete event: ${response.status}`);
} else {
alert(`Event deleted`);
}
}
const Calendar = () => {
const [selectedDate, setSelectedDate] = useState(new Date());
const [events, setEvents] = useState([]);
Expand Down Expand Up @@ -34,7 +48,7 @@ const Calendar = () => {
headers: { 'Authorization': 'Bearer ' + session.provider_token,}
});

if (!response.ok) {
if (!response||!response.ok) {
console.error('Error fetching events');
return;
}
Expand Down Expand Up @@ -65,25 +79,12 @@ const handleEventClick = async (eventId) => {
alert(`Event details:\n\nName: ${event.summary}\n\nEvent starts at: ${startTime}\nEvent ends at: ${endTime}\n`);
const shouldDelete = window.confirm('Do you want to delete this event?');
if(shouldDelete){
await deleteEvent(eventId);
await deleteEvent(eventId,session.provider_token);
handleDayClick(selectedDate.getDate());
}
};

async function deleteEvent(eventId) {
const response = await fetch(`https://www.googleapis.com/calendar/v3/calendars/primary/events/${eventId}`, {
method: "DELETE",
headers: {
'Authorization': 'Bearer ' + session.provider_token, // Access token for Google
},
});

if (!response.ok) {
throw new Error(`Failed to delete event: ${response.status}`);
} else {
alert(`Event deleted`);
}
}
const renderCalendar = () => {


Expand Down
3 changes: 3 additions & 0 deletions src/component/calendarComponent/input_field.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,20 @@ function InputField(props) {
<div>
<input
type="date"
placeholder="date"
value={date}
onChange={(e) => setDate(e.target.value)}
/>
<input
type="time"
placeholder="start time"
value={time}
onChange={(e) => setTime(e.target.value)}
/>
<span>Until</span>
<input
type="time"
placeholder="end time"
value={endTime} // Use the new state variable here
onChange={(e) => setEndTime(e.target.value)} // And here
/>
Expand Down