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

562 2 tests #563

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
79 changes: 79 additions & 0 deletions edit-user-role-page.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { render, screen, waitFor } from '@testing-library/react';
import EditUserRolePage from '@/app/edit-user-role-page/page';
import fetchMock from 'jest-fetch-mock';

jest.mock('../../../components/UserCard', () => {
return function MockUserCard({ user }: { user: any }) {
return <div data-testid="user-card">{user.firstName} {user.lastName}</div>;
};
});

jest.mock('../../../components/UnauthorizedPageMessage', () => {
return function MockUnauthorizedMessage() {
return <div data-testid="unauthorized-message">Unauthorized</div>;
};
});


describe('EditUserRolePage Component', () => {
beforeEach(() => {
fetchMock.resetMocks();
localStorage.clear();
});

test('renders User Management page for admin users and displays user info', async () => {
// Mock localStorage for admin role
const mockToken = JSON.stringify({
role: 'admin',
});
localStorage.setItem(
'token',
`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(mockToken)}.signature`
);

// Mock user data fetch
const mockUsers = [
{ id: '1', firstName: 'John', lastName: 'Doe', email: '[email protected]', role: 'editor' },
{ id: '2', firstName: 'Jane', lastName: 'Smith', email: '[email protected]', role: 'viewer' },
];
fetchMock.mockResponseOnce(JSON.stringify(mockUsers));

render(<EditUserRolePage />);

// Wait for the page to render users
await waitFor(() => {
expect(screen.getByText(/User Management/i)).toBeInTheDocument();
expect(screen.getAllByTestId('user-card')).toHaveLength(2);
expect(screen.getByText(/John Doe/i)).toBeInTheDocument();
expect(screen.getByText(/Jane Smith/i)).toBeInTheDocument();
});
});

test('renders UnauthorizedPageMessage for non-admin users', async () => {
// Mock localStorage for non-admin role
const mockToken = JSON.stringify({
role: 'viewer',
});
localStorage.setItem(
'token',
`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(mockToken)}.signature`
);

render(<EditUserRolePage />);

// Check unauthorized message is displayed
await waitFor(() => {
expect(screen.getByTestId('unauthorized-message')).toBeInTheDocument();
});
});

test('handles missing or invalid token gracefully', async () => {
// No token in localStorage
render(<EditUserRolePage />);

// Check unauthorized message is displayed
await waitFor(() => {
expect(screen.getByTestId('unauthorized-message')).toBeInTheDocument();
});
});
});
41 changes: 41 additions & 0 deletions form-page.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { render, screen, fireEvent } from '@testing-library/react';
import FormPage from '@/app/form-page/page';

describe('FormPage Component', () => {
test('renders the form with all fields and a submit button', () => {
render(<FormPage />);

// Check if form elements are rendered
expect(screen.getByText(/Belinda's Closet Student Form/i)).toBeInTheDocument();
expect(screen.getByLabelText(/Name/i)).toBeInTheDocument();
expect(screen.getByLabelText(/Gender/i)).toBeInTheDocument();
expect(screen.getByLabelText(/Email/i)).toBeInTheDocument();
expect(screen.getByLabelText(/Size/i)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Submit/i })).toBeInTheDocument();
});

test('allows user to type in form fields and submit the form', () => {
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {}); // Spy on console.log

render(<FormPage />);

// Fill out the form
fireEvent.change(screen.getByLabelText(/Name/i), { target: { value: 'John Doe' } });
fireEvent.change(screen.getByLabelText(/Gender/i), { target: { value: 'Male' } });
fireEvent.change(screen.getByLabelText(/Email/i), { target: { value: '[email protected]' } });
fireEvent.change(screen.getByLabelText(/Size/i), { target: { value: 'M' } });

// Submit the form
fireEvent.click(screen.getByRole('button', { name: /Submit/i }));

// Check if console.log was called with the correct form data
expect(consoleSpy).toHaveBeenCalledWith('Form submitted:', {
name: 'John Doe',
gender: 'Male',
email: '[email protected]',
size: 'M',
});

consoleSpy.mockRestore(); // Clean up the mock
});
});
38 changes: 21 additions & 17 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
const nextJest = require('next/jest');

const createJestConfig = nextJest({
dir: './',
});

// Add any custom config to be passed to Jest
/** @type {import('jest').Config} */
const config = {
// Add more setup options before each test is run
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testEnvironment: 'jest-environment-jsdom',
preset: 'ts-jest',
};

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(config);
const nextJest = require('next/jest');

const createJestConfig = nextJest({
dir: './',
});

// Custom Jest configuration
/** @type {import('jest').Config} */
const customJestConfig = {
// Resolve module aliases
moduleNameMapper: {
'^@/components/(.*)$': '<rootDir>/components/$1', // Maps @/components to the components folder
'^@/(.*)$': '<rootDir>/$1', // Maps @/ to the root folder
},
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'], // Ensure setup is loaded before tests
testEnvironment: 'jest-environment-jsdom', // Use jsdom for DOM-related tests
preset: 'ts-jest', // TypeScript support
};

// Export the Jest configuration
module.exports = createJestConfig(customJestConfig);
48 changes: 29 additions & 19 deletions jest.setup.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,29 @@
import '@testing-library/jest-dom';

// Old import replaced by the one above: import '@testing-library/jest-dom/extend-expect';

// Trying to suppress console.error for creator page test (Error: Not implemented: navigation (except hash changes), this solution fails.

/*
const originalConsoleError = console.error;

console.error = (...args) => {
if (typeof args[0] === 'string' && args[0].includes('Not implemented: navigation (except hash changes)')) {
return; // Suppress the specific warning
}
originalConsoleError(...args); // Call the original console.error
};
*/



import '@testing-library/jest-dom';

import fetchMock from 'jest-fetch-mock';
fetchMock.enableMocks();

module.exports = {
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
};


// Old import replaced by the one above: import '@testing-library/jest-dom/extend-expect';

// Trying to suppress console.error for creator page test (Error: Not implemented: navigation (except hash changes), this solution fails.

/*
const originalConsoleError = console.error;

console.error = (...args) => {
if (typeof args[0] === 'string' && args[0].includes('Not implemented: navigation (except hash changes)')) {
return; // Suppress the specific warning
}
originalConsoleError(...args); // Call the original console.error
};
*/



Loading
Loading