Skip to content

Commit

Permalink
more integration tests for calendar features
Browse files Browse the repository at this point in the history
  • Loading branch information
abdurisaq committed Dec 7, 2023
1 parent c5f00c9 commit 9e70e67
Show file tree
Hide file tree
Showing 3 changed files with 204 additions and 15 deletions.
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',
}),
})
);
});
});

});
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

0 comments on commit 9e70e67

Please sign in to comment.