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

Tests for Navbar, Login and BookmarkRecipe component #14

Merged
merged 1 commit into from
Nov 1, 2024
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
3 changes: 0 additions & 3 deletions Code/frontend/src/components/Navbar.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import {
Center,
Heading
} from '@chakra-ui/react'
import SearchBar from './SearchBar'
import logo from '../Images/logo.png';

const NavLink = (props) => {
Expand All @@ -41,8 +40,6 @@ const NavLink = (props) => {
}

export default function Nav(props) {
const { colorMode, toggleColorMode } = useColorMode()
const { isOpen, onOpen, onClose } = useDisclosure()

return (
<Box bg="#D3D3D3" color={"black"} mb={5} px={4}>
Expand Down
101 changes: 101 additions & 0 deletions Code/frontend/src/components/__tests__/Navbar.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import Nav from '../Navbar';

jest.mock('@chakra-ui/react', () => {
return {
Box: ({ children, ...props }) => <div {...props}>{children}</div>,
Flex: ({ children, ...props }) => <div {...props}>{children}</div>,
Avatar: ({ dataTestId = 'mock-avatar', ...props }) => <div data-testid={dataTestId} {...props} />,
Text: (props) => <span {...props}>{props.children}</span>,
Button: ({ children, ...props }) => <button {...props}>{children}</button>,
Menu: ({ children }) => <div>{children}</div>,
MenuButton: ({ children }) => <button>{children}</button>,
MenuList: ({ children }) => <div>{children}</div>,
MenuItem: ({ children, onClick }) => <div onClick={onClick}>{children}</div>,
MenuDivider: () => <hr />,
Stack: ({ children, ...props }) => <div {...props}>{children}</div>,
Center: ({ children, ...props }) => <div style={{ textAlign: 'center' }} {...props}>{children}</div>,
Heading: ({ children, ...props }) => <h1 {...props}>{children}</h1>,
};
});

describe('Navbar component', () => {
const mockHandleBookMarks = jest.fn();
const mockHandleLogout = jest.fn();
const mockToggleLoginModal = jest.fn();

test('renders logo and app name', () => {
render(<Nav />);
const logoImg = screen.getByRole('img');
const appName = screen.getByText('CookSmart');

expect(logoImg).toBeInTheDocument();
expect(appName).toBeInTheDocument();
});

test('renders login button when user is not logged in', () => {
render(<Nav toggleLoginModal={mockToggleLoginModal} userLoggedIn={false} />);
const loginButton = screen.getByRole('button', { name: /login/i });

expect(loginButton).toBeInTheDocument();
});

test('calls toggleLoginModal when login button is clicked', () => {
render(<Nav toggleLoginModal={mockToggleLoginModal} userLoggedIn={false} />);
const loginButton = screen.getByRole('button', { name: /login/i });
fireEvent.click(loginButton);

expect(mockToggleLoginModal).toHaveBeenCalledTimes(1);
});

test('displays user avatar and email when logged in', () => {
render(
<Nav
userLoggedIn={true}
currentUser={{ email: 'test@example.com' }}
handleBookMarks={mockHandleBookMarks}
handleLogout={mockHandleLogout}
/>
);

const avatar = screen.getAllByTestId('mock-avatar');
fireEvent.click(avatar[0]);

expect(screen.getByText('test@example.com')).toBeInTheDocument();
});

test('calls handleBookMarks when Bookmarks menu item is clicked', () => {
render(
<Nav
userLoggedIn={true}
currentUser={{ email: 'test@example.com' }}
handleBookMarks={mockHandleBookMarks}
handleLogout={mockHandleLogout}
/>
);

fireEvent.click(screen.getAllByTestId('mock-avatar')[0]);
const bookmarksItem = screen.getByText(/bookmarks/i);
fireEvent.click(bookmarksItem);

expect(mockHandleBookMarks).toHaveBeenCalledTimes(1);
});

test('calls handleLogout when Logout menu item is clicked', () => {
render(
<Nav
userLoggedIn={true}
currentUser={{ email: 'test@example.com' }}
handleBookMarks={mockHandleBookMarks}
handleLogout={mockHandleLogout}
/>
);

fireEvent.click(screen.getAllByTestId('mock-avatar')[0]);
const logoutItem = screen.getByText(/logout/i);
fireEvent.click(logoutItem);

expect(mockHandleLogout).toHaveBeenCalledTimes(1);
});
});
47 changes: 47 additions & 0 deletions Code/frontend/src/components/__tests__/SearchBlock.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import SearchBlock from '../SearchBlock';
import { fetchBookmarkedRecipes, fetchBookmarkedIngredients, bookmarkRecipe, unbookmarkRecipe, isRecipeBookmarked } from '../../service/firestoreService';
import { useAuth } from '../../contexts/authContext/index';
import axios from 'axios';
import jsPDF from 'jspdf';

jest.setTimeout(20000);

jest.mock('axios');
jest.mock('jspdf');
jest.mock('../../contexts/authContext/index', () => ({
useAuth: jest.fn(),
}));
jest.mock('../../service/firestoreService', () => ({
bookmarkRecipe: jest.fn(),
unbookmarkRecipe: jest.fn(),
isRecipeBookmarked: jest.fn(),
}));

describe('SearchBlock Component', () => {
beforeEach(() => {
useAuth.mockReturnValue({ userLoggedIn: true });
axios.post.mockResolvedValue({
data: {
recipes: [
{ name: 'Pasta', ingredients: ['Tomato', 'Basil'], tags: ['Italian'], time: '30 minutes' },
{ name: 'Salad', ingredients: ['Lettuce', 'Carrot'], tags: ['Healthy'], time: '10 minutes' }
],
ingredients: ['Tomato', 'Basil']
}
});
jsPDF.mockImplementation(() => ({
save: jest.fn(),
}));
});

afterEach(() => {
jest.clearAllMocks();
});

test('renders correctly', () => {
render(<SearchBlock />);
expect(screen.getByPlaceholderText(/Add ingredients or search by name/i)).toBeInTheDocument();
});
});
5 changes: 0 additions & 5 deletions Code/frontend/src/service/firestoreService.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { bookmarkRecipe, unbookmarkRecipe, isRecipeBookmarked, fetchBookmarkedRe
import { auth, db } from "../firebase/firebase";
import { doc, setDoc, deleteDoc, getDoc, getDocs, query, where, collection } from "firebase/firestore";

// Mock Firebase imports
jest.mock("firebase/firestore", () => ({
doc: jest.fn(),
setDoc: jest.fn(),
Expand Down Expand Up @@ -113,7 +112,6 @@ describe("firestoreService", () => {
});

test('fetchBookmarkedIngredients should return all unique ingredients', async () => {
// Arrange
const bookmarksRef = { id: 'bookmarksRef' };
const mockData = [
{ userId: 'testUserId', recipeName: 'Recipe 1', ingredients: ['Ingredient 1', 'Ingredient 2'], cookingTime: '30 mins', steps: 'Step 1' },
Expand All @@ -124,7 +122,6 @@ describe("firestoreService", () => {
query.mockReturnValue('mockedQuery');
where.mockReturnValue('mockedWhere');

// Mocking getDocs to return an iterable object with a forEach method
getDocs.mockResolvedValue({
docs: mockData.map(data => ({
data: () => data
Expand All @@ -134,10 +131,8 @@ describe("firestoreService", () => {
}
});

// Act
const ingredients = await fetchBookmarkedIngredients();

// Assert
expect(ingredients).toEqual(['Ingredient 1', 'Ingredient 2', 'Ingredient 3']);
expect(collection).toHaveBeenCalledWith(expect.anything(), "bookmarks");
expect(query).toHaveBeenCalled();
Expand Down
Loading