Skip to content

Commit

Permalink
added allowed users
Browse files Browse the repository at this point in the history
  • Loading branch information
deepikagonuguntla committed Jul 22, 2024
1 parent abc8b13 commit 7cc51fa
Show file tree
Hide file tree
Showing 11 changed files with 206 additions and 71 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,6 @@ function AccountDetailsSubMenu(props) {
const signOut = () => {
axios
.delete("/users/logout", {
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": document
.querySelector("meta[name='csrf-token']")
.getAttribute("content"),
},
})
.then((res) => {
if (res.data.status === 200 && res.data.logged_out === true) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { render, screen, cleanup, waitFor } from "@testing-library/react";
import { render, screen, cleanup, waitFor, fireEvent } from "@testing-library/react";
import '@testing-library/jest-dom/extend-expect';
import * as React from "react";
import AccountDetailsSubMenu from "../AccountDetailsSubMenu/AccountDetailsSubMenu.jsx";
Expand All @@ -23,39 +23,93 @@ jest.mock('react-router-dom', () => ({
}));

describe("AccountDetailsSubMenu", () => {
it ('should render Account menu', async () => {
it ('should render SignIn menu', async () => {
const rootElement = document.createElement('div');
document.body.appendChild(rootElement);
const root = createRoot(rootElement);

// Call the function with mock parameters (if required)
await act(async () => {
root.render(<AccountDetailsSubMenu userSignedIn={true} />);
root.render(<AccountDetailsSubMenu userSignedIn={false} />);
});

// Find the anchor element by its text content
const accountLink = screen.getByText('My Account');
const accountLink = screen.getByText('Sign In');

// Assert the href attribute
expect(accountLink).toHaveAttribute('href', '/account_details');
expect(accountLink).toHaveAttribute('href', '/signin');
expect(accountLink).toBeInTheDocument();
expect(screen.getByText('Sign In')).toBeInTheDocument();
});

it ('should render SignIn menu', async () => {
it ("should render about menu", async () => {
const rootElement = document.createElement('div');
document.body.appendChild(rootElement);
const root = createRoot(rootElement);

jest.mock('', () => ({
useNYPLBreakpoints: jest.fn(() => ({
isLargerThanMedium: true,
isLargerThanMobile: false,
})),
handleHover: jest.fn(),
useColorModeValue: jest.fn().mockReturnValue({
color: 'light-color-value',
}),
}));

// Call the function with mock parameters (if required)
await act(async () => {
root.render(<AccountDetailsSubMenu userSignedIn={false} />);
root.render(<MemoryRouter><AccountDetailsSubMenu userSignedIn={true} /></MemoryRouter>);
});

// Find the anchor element by its text content
const accountLink = screen.getByText('Sign In');

// Assert the href attribute
expect(accountLink).toHaveAttribute('href', '/signin');
expect(accountLink).toBeInTheDocument();
const accountLink = screen.getByText('My Account');

// Assert that the link is rendered
const linkElement = screen.getByText('My Account');
expect(linkElement).toBeInTheDocument();

// Simulate mouse enter event on the link
fireEvent.mouseEnter(linkElement);

expect(screen.getByText('Settings')).toBeInTheDocument();
expect(screen.getByText('My orders')).toBeInTheDocument();
expect(screen.getByText('Sign out')).toBeInTheDocument();
});
});

describe('SignOutLink', () => {
it('calls signOut function on click', async () => {
const rootElement = document.createElement('div');
document.body.appendChild(rootElement);
const root = createRoot(rootElement);

// Mock props
const props = {
colorMode: 'light',
handleLogout: jest.fn(),
setShowAboutMenu: jest.fn(),
handleSignOutMsg: jest.fn(),
hideSignUpMessage: jest.fn(),
};

// Mock Axios delete request
axios.delete.mockResolvedValueOnce({ data: { status: 200, logged_out: true, sign_out_msg: 'Signed out successfully' } });


await act(async () => {
root.render(<MemoryRouter><AccountDetailsSubMenu {...props} /></MemoryRouter>);
});

// Simulate click on sign out link
fireEvent.click(screen.getByText('Sign out'));

// Wait for Axios request to resolve
await act(async () => {
await axios.delete;
});

// Assertions
expect(axios.delete).toHaveBeenCalledWith('/users/logout', {});
});
});
});
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState, useEffect } from "react";
import AppBreadcrumbs from "./AppBreadcrumbs";
import HaveQuestions from "./HaveQuestions/HaveQuestions";
import AppBreadcrumbs from "../AppBreadcrumbs";
import HaveQuestions from "../HaveQuestions/HaveQuestions";
import axios from "axios";

import {
Expand Down Expand Up @@ -58,9 +58,6 @@ export default function Accounts() {
useEffect(() => {
window.scrollTo(0, 0);
document.title = "Account Details | MyLibraryNYC";
axios.defaults.headers.common["X-CSRF-TOKEN"] = document
.querySelector("meta[name='csrf-token']")
.getAttribute("content");

axios
.get("/account", { params: { page: 1 } })
Expand Down Expand Up @@ -313,9 +310,6 @@ export default function Accounts() {
};

const onPageChange = (page) => {
axios.defaults.headers.common["X-CSRF-TOKEN"] = document
.querySelector("meta[name='csrf-token']")
.getAttribute("content");
axios
.get("/account", { params: { page: page } })
.then((res) => {
Expand Down
90 changes: 90 additions & 0 deletions app/javascript/components/Accounts/Accounts.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@

import { render, screen, cleanup, waitFor, fireEvent } from "@testing-library/react";
import '@testing-library/jest-dom/extend-expect';
import * as React from "react";
import Accounts from "../Accounts/Accounts.jsx";
import { createRoot } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
import axios from 'axios';
import { MemoryRouter } from 'react-router-dom';
jest.mock('axios');

// Mock useLocation
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'), // Use actual react-router-dom for other functions
useLocation: jest.fn().mockReturnValue({
pathname: '/mock-path',
search: '',
hash: '',
state: null,
key: 'testKey',
}),
useNavigate: jest.fn(), // Mock useNavigate if needed
useHref: jest.fn(), // Mock useHref if needed
}));

describe('Accounts', () => {
it('fetches account details on mount', async () => {
const mockAccountDetails = {
email: 'test@example.com',
alt_email: 'alt@example.com',
schools: ['School A', 'School B'],
current_user: 'User A',
holds: ['Hold 1', 'Hold 2'],
school: { id: 'school_id' },
current_password: 'password123',
total_pages: 10,
ordersNotPresentMsg: 'No orders found',
};

axios.get.mockResolvedValueOnce({ data: { accountdetails: mockAccountDetails }, request: { responseURL: env.MLN_INFO_SITE_HOSTNAME + '/account', status: 200 } });

const rootElement = document.createElement('div');
document.body.appendChild(rootElement);
const root = createRoot(rootElement);

// Call the function with mock parameters (if required)
await act(async () => {
root.render(<Accounts />);
});

// Wait for Axios request to resolve
await waitFor(() => {
expect(axios.get).toHaveBeenCalledWith('/account', { params: { page: 1 } }); // Verify axios.get call
// Assertions for state updates based on mocked data
expect(screen.getByText('Preferred email address for reservation notifications')).toBeInTheDocument();
expect(document.title).toBe("Account Details | MyLibraryNYC"); // Verify document title
});
});

it('no orders found', async () => {
const mockAccountDetails = {
email: 'test@example.com',
alt_email: 'alt@example.com',
schools: ['School A', 'School B'],
current_user: 'User A',
holds: [],
school: { id: 'school_id' },
current_password: 'password123',
total_pages: 10,
ordersNotPresentMsg: 'No orders found',
};

axios.get.mockResolvedValueOnce({ data: { accountdetails: mockAccountDetails }, request: { responseURL: env.MLN_INFO_SITE_HOSTNAME + '/account', status: 200 } });

const rootElement = document.createElement('div');
document.body.appendChild(rootElement);
const root = createRoot(rootElement);

// Call the function with mock parameters (if required)
await act(async () => {
root.render(<Accounts />);
});

// Wait for Axios request to resolve
expect(axios.get).toHaveBeenCalledWith('/account', { params: { page: 1 } }); // Verify axios.get call
// Assertions for state updates based on mocked data
expect(document.title).toBe("Account Details | MyLibraryNYC"); // Verify document title
expect(screen.getByText('You have not yet placed any orders.')).toBeInTheDocument();
});
});
2 changes: 1 addition & 1 deletion app/javascript/components/NavBar/Navbar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
useColorModeValue,
} from "@nypl/design-system-react-components";

import AccountDetailsSubMenu from "./../AccountDetailsSubMenu";
import AccountDetailsSubMenu from "../AccountDetailsSubMenu/AccountDetailsSubMenu";
import ColorModeComponent from "./../ColorMode/ColorMode";

export default function Navbar(props) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,6 @@ export default function SearchTeacherSets(props) {
};

const teacherSetTitleOrder = () => {
console.log("ppppppppp")
if (teacherSets.length >= 1) {
let sortByOptions = [
{ sort_order: "Date added: newest to oldest", value: 0 },
Expand Down Expand Up @@ -1191,7 +1190,6 @@ export default function SearchTeacherSets(props) {

const tsDataNotRetrievedMsg = () => {
if (teacherSetDataNotRetrievedMsg !== "") {
console.log("eeeeeeee")
return (
<Notification
marginTop="l"
Expand Down Expand Up @@ -1265,4 +1263,4 @@ export default function SearchTeacherSets(props) {
sidebar="left"
/>
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import {
useColorMode,
} from "@nypl/design-system-react-components";

import mlnImage from "../images/mln.svg";
import mlnImage from "../../images/mln.svg";

export default function TeacherSetDetails(props) {
const params = useParams();
Expand Down
2 changes: 1 addition & 1 deletion app/javascript/routes/AppRoutes.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import ParticipatingSchools from "../components/ParticipatingSchools/Participati
import SignIn from "../components/SignIn/SignIn";
import SignUp from "../components/SignUp/SignUp";
import SearchTeacherSets from "../components/SearchTeacherSets/SearchTeacherSets";
import Accounts from "../components/Accounts";
import Accounts from "../components/Accounts/Accounts";
import MobileNavbarSubmenu from "../components/MobileNavbarSubmenu";
import TeacherSetDetails from "../components/TeacherSetDetails/TeacherSetDetails";
import TeacherSetOrder from "../components/TeacherSetOrder/TeacherSetOrder";
Expand Down
7 changes: 6 additions & 1 deletion db/seed-data.sql
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,13 @@ SELECT pg_catalog.setval('users_id_seq', 76895, true);
-- Data for Name: admin_users; Type: TABLE DATA; Schema: public; Owner: _postgres
--

INSERT INTO admin_users (id, email, encrypted_password, reset_password_token, reset_password_sent_at, remember_created_at, sign_in_count, current_sign_in_at, last_sign_in_at, current_sign_in_ip, last_sign_in_ip, created_at, updated_at) VALUES (1, 'admin@example.com', '$2a$10$xrSNKn4ymrSoHwdkX6Zhw.sOg0LDH2v1dRrLgMQDDbx2A/84hH9A.', NULL, NULL, NULL, 12, '2014-02-07 17:46:00.404514', '2014-02-07 17:44:25.821704', '127.0.0.1', '127.0.0.1', '2014-01-09 15:59:50.223609', '2014-02-07 17:46:00.406525');
INSERT INTO admin_users (id, email, encrypted_password, reset_password_token, reset_password_sent_at, remember_created_at, sign_in_count, current_sign_in_at, last_sign_in_at, current_sign_in_ip, last_sign_in_ip, created_at, updated_at) VALUES (1, 'consultdg@nypl.org', 'password', NULL, NULL, NULL, 12, '2014-02-07 17:46:00.404514', '2014-02-07 17:44:25.821704', '127.0.0.1', '127.0.0.1', '2014-01-09 15:59:50.223609', '2014-02-07 17:46:00.406525');

--
-- Data for Name: admin_users; Type: TABLE DATA; Schema: public; Owner: _postgres
--

INSERT INTO allowed_user_email_masks (id, email_pattern, active) VALUES (1, '@schools.nyc.gov', 'password', true);

--
-- Data for Name: books; Type: TABLE DATA; Schema: public; Owner: _postgres
Expand Down
46 changes: 23 additions & 23 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
module.exports = {
collectCoverage: true,
collectCoverageFrom: ['<rootDir>/app/javascript/components/**/*.{js,jsx,tsx,ts}',
"!**/*.d.ts",
"!**/node_modules/**",
],
coverageDirectory: 'coverage',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testPathIgnorePatterns: [
"/node_modules/",
"/lib",
"/config",
"<rootDir>/app/javascript/styles/application.scss",
],
transformIgnorePatterns: [
"./node_modules/",
"^.+\\.module\\.(css|sass|scss)$",
],
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/app/javascript/components/Home/Home.test.tsx",
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy",
}
collectCoverage: true,
collectCoverageFrom: ['<rootDir>/app/javascript/components/**/*.{js,jsx,tsx,ts}',
"!**/*.d.ts",
"!**/node_modules/**",
],
coverageDirectory: 'coverage',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testPathIgnorePatterns: [
"/node_modules/",
"/lib",
"/config",
"<rootDir>/app/javascript/styles/application.scss",
],
transformIgnorePatterns: [
"./node_modules/",
"^.+\\.module\\.(css|sass|scss)$",
],
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/app/javascript/components/Home/Home.test.tsx",
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy",
}
}
Loading

0 comments on commit 7cc51fa

Please sign in to comment.