feat: add frontend test coverage for date-utils, api interceptors, AuthGuard, QueryProvider, DashboardLayout

Agent-Logs-Url: https://github.com/christianlouis/InboxConverge/sessions/6b527e29-8e26-4f86-88e2-847687f759ad

Co-authored-by: christianlouis <361235+christianlouis@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot]
2026-03-29 00:00:08 +00:00
parent 7dd0b5f600
commit 63839c3886
9 changed files with 966 additions and 0 deletions
+2
View File
@@ -6,6 +6,7 @@ const createJestConfig = nextJest({
const customJestConfig = {
testEnvironment: 'jest-environment-jsdom',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
@@ -16,6 +17,7 @@ const customJestConfig = {
'!src/**/layout.tsx',
'!src/**/page.tsx',
'!src/instrumentation.ts',
'!src/test-setup.ts',
],
};
+262
View File
@@ -18,6 +18,9 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",
"@types/jest": "^30.0.0",
"@types/node": "^20",
"@types/react": "^19",
@@ -30,6 +33,13 @@
"typescript": "^5"
}
},
"node_modules/@adobe/css-tools": {
"version": "4.4.4",
"resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.4.tgz",
"integrity": "sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==",
"dev": true,
"license": "MIT"
},
"node_modules/@alloc/quick-lru": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz",
@@ -518,6 +528,16 @@
"@babel/core": "^7.0.0-0"
}
},
"node_modules/@babel/runtime": {
"version": "7.29.2",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",
"integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/template": {
"version": "7.28.6",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz",
@@ -2678,6 +2698,156 @@
"react": "^18 || ^19"
}
},
"node_modules/@testing-library/dom": {
"version": "10.4.1",
"resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz",
"integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.10.4",
"@babel/runtime": "^7.12.5",
"@types/aria-query": "^5.0.1",
"aria-query": "5.3.0",
"dom-accessibility-api": "^0.5.9",
"lz-string": "^1.5.0",
"picocolors": "1.1.1",
"pretty-format": "^27.0.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@testing-library/dom/node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=8"
}
},
"node_modules/@testing-library/dom/node_modules/ansi-styles": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/@testing-library/dom/node_modules/aria-query": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz",
"integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==",
"dev": true,
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"dequal": "^2.0.3"
}
},
"node_modules/@testing-library/dom/node_modules/pretty-format": {
"version": "27.5.1",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"ansi-regex": "^5.0.1",
"ansi-styles": "^5.0.0",
"react-is": "^17.0.1"
},
"engines": {
"node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0"
}
},
"node_modules/@testing-library/dom/node_modules/react-is": {
"version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true,
"license": "MIT",
"peer": true
},
"node_modules/@testing-library/jest-dom": {
"version": "6.9.1",
"resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz",
"integrity": "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@adobe/css-tools": "^4.4.0",
"aria-query": "^5.0.0",
"css.escape": "^1.5.1",
"dom-accessibility-api": "^0.6.3",
"picocolors": "^1.1.1",
"redent": "^3.0.0"
},
"engines": {
"node": ">=14",
"npm": ">=6",
"yarn": ">=1"
}
},
"node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz",
"integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==",
"dev": true,
"license": "MIT"
},
"node_modules/@testing-library/react": {
"version": "16.3.2",
"resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.2.tgz",
"integrity": "sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.12.5"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@testing-library/dom": "^10.0.0",
"@types/react": "^18.0.0 || ^19.0.0",
"@types/react-dom": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0",
"react-dom": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@testing-library/user-event": {
"version": "14.6.1",
"resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.1.tgz",
"integrity": "sha512-vq7fv0rnt+QTXgPxr5Hjc210p6YKq2kmdziLgnsZGgLJ9e6VAShx1pACLuRjd/AS/sr7phAR58OIIpf0LlmQNw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12",
"npm": ">=6"
},
"peerDependencies": {
"@testing-library/dom": ">=7.21.4"
}
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.1",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz",
@@ -2689,6 +2859,14 @@
"tslib": "^2.4.0"
}
},
"node_modules/@types/aria-query": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
"dev": true,
"license": "MIT",
"peer": true
},
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@@ -4238,6 +4416,13 @@
"node": ">= 8"
}
},
"node_modules/css.escape": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz",
"integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==",
"dev": true,
"license": "MIT"
},
"node_modules/cssstyle": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz",
@@ -4436,6 +4621,17 @@
"node": ">=0.4.0"
}
},
"node_modules/dequal": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
"integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=6"
}
},
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -4469,6 +4665,14 @@
"node": ">=0.10.0"
}
},
"node_modules/dom-accessibility-api": {
"version": "0.5.16",
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
"dev": true,
"license": "MIT",
"peer": true
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
@@ -6082,6 +6286,16 @@
"node": ">=0.8.19"
}
},
"node_modules/indent-string": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz",
"integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
@@ -7891,6 +8105,17 @@
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/lz-string": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"lz-string": "bin/bin.js"
}
},
"node_modules/magic-string": {
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
@@ -8011,6 +8236,16 @@
"node": ">=6"
}
},
"node_modules/min-indent": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz",
"integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/minimatch": {
"version": "10.2.4",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz",
@@ -8855,6 +9090,20 @@
"dev": true,
"license": "MIT"
},
"node_modules/redent": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz",
"integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==",
"dev": true,
"license": "MIT",
"dependencies": {
"indent-string": "^4.0.0",
"strip-indent": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/reflect.getprototypeof": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
@@ -9690,6 +9939,19 @@
"node": ">=6"
}
},
"node_modules/strip-indent": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz",
"integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"min-indent": "^1.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-json-comments": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
+3
View File
@@ -21,6 +21,9 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",
"@types/jest": "^30.0.0",
"@types/node": "^20",
"@types/react": "^19",
+145
View File
@@ -0,0 +1,145 @@
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import { AuthGuard } from './AuthGuard';
// Mock next/navigation
const mockPush = jest.fn();
jest.mock('next/navigation', () => ({
useRouter: () => ({ push: mockPush }),
}));
// Mock userApi
const mockGetCurrentUser = jest.fn();
jest.mock('@/lib/api', () => ({
userApi: {
getCurrentUser: (...args: unknown[]) => mockGetCurrentUser(...args),
},
}));
// Mock authStore
const mockSetUser = jest.fn();
const mockSetLoading = jest.fn();
let mockUser: Record<string, unknown> | null = null;
let mockIsLoading = true;
jest.mock('@/store/authStore', () => ({
useAuthStore: () => ({
user: mockUser,
isLoading: mockIsLoading,
setUser: mockSetUser,
setLoading: mockSetLoading,
}),
}));
const mockUserData = {
id: 1,
email: 'test@example.com',
full_name: 'Test User',
is_active: true,
is_superuser: false,
subscription_tier: 'free',
subscription_status: 'active',
created_at: '2024-01-01T00:00:00Z',
};
describe('AuthGuard', () => {
beforeEach(() => {
jest.clearAllMocks();
localStorage.clear();
mockUser = null;
mockIsLoading = true;
});
it('should show loading spinner while isLoading is true', () => {
mockIsLoading = true;
localStorage.setItem('access_token', 'test-token');
mockGetCurrentUser.mockResolvedValue(mockUserData);
render(
<AuthGuard>
<div>Protected Content</div>
</AuthGuard>
);
// Should show spinner (via animate-spin class)
const spinner = document.querySelector('.animate-spin');
expect(spinner).toBeInTheDocument();
expect(screen.queryByText('Protected Content')).not.toBeInTheDocument();
});
it('should render children when user is authenticated', () => {
mockUser = mockUserData;
mockIsLoading = false;
localStorage.setItem('access_token', 'test-token');
render(
<AuthGuard>
<div>Protected Content</div>
</AuthGuard>
);
expect(screen.getByText('Protected Content')).toBeInTheDocument();
});
it('should render nothing when not loading and no user', () => {
mockUser = null;
mockIsLoading = false;
const { container } = render(
<AuthGuard>
<div>Protected Content</div>
</AuthGuard>
);
expect(screen.queryByText('Protected Content')).not.toBeInTheDocument();
expect(container.innerHTML).toBe('');
});
it('should redirect to /login when no token exists', async () => {
// No token in localStorage
mockGetCurrentUser.mockResolvedValue(mockUserData);
render(
<AuthGuard>
<div>Protected Content</div>
</AuthGuard>
);
await waitFor(() => {
expect(mockSetLoading).toHaveBeenCalledWith(false);
expect(mockPush).toHaveBeenCalledWith('/login');
});
});
it('should fetch user data when token exists', async () => {
localStorage.setItem('access_token', 'valid-token');
mockGetCurrentUser.mockResolvedValue(mockUserData);
render(
<AuthGuard>
<div>Protected Content</div>
</AuthGuard>
);
await waitFor(() => {
expect(mockGetCurrentUser).toHaveBeenCalled();
expect(mockSetUser).toHaveBeenCalledWith(mockUserData);
});
});
it('should redirect to /login when API call fails', async () => {
localStorage.setItem('access_token', 'expired-token');
mockGetCurrentUser.mockRejectedValue(new Error('Unauthorized'));
render(
<AuthGuard>
<div>Protected Content</div>
</AuthGuard>
);
await waitFor(() => {
expect(mockSetUser).toHaveBeenCalledWith(null);
expect(mockPush).toHaveBeenCalledWith('/login');
});
});
});
@@ -0,0 +1,246 @@
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { DashboardLayout } from './DashboardLayout';
// Mock next/navigation
const mockPush = jest.fn();
let mockPathname = '/dashboard';
jest.mock('next/navigation', () => ({
usePathname: () => mockPathname,
useRouter: () => ({ push: mockPush }),
}));
// Mock next/link to render a simple anchor
jest.mock('next/link', () => {
return ({ children, href, ...props }: { children: React.ReactNode; href: string; [key: string]: unknown }) => (
<a href={href} {...props}>{children}</a>
);
});
// Mock @tanstack/react-query
let mockVersionInfo: Record<string, string> | null = null;
jest.mock('@tanstack/react-query', () => ({
useQuery: () => ({ data: mockVersionInfo }),
}));
// Mock lucide-react icons as simple spans
jest.mock('lucide-react', () => {
const iconNames = [
'LayoutDashboard', 'Mail', 'Settings', 'LogOut', 'Menu', 'X',
'User', 'Shield', 'Users', 'CreditCard', 'Bell', 'Inbox', 'Activity',
];
const icons: Record<string, React.FC<{ className?: string }>> = {};
iconNames.forEach((name) => {
icons[name] = ({ className }: { className?: string }) => (
<span data-testid={`icon-${name}`} className={className} />
);
});
return icons;
});
// Mock authStore
const mockLogout = jest.fn();
let mockUser: Record<string, unknown> | null = null;
jest.mock('@/store/authStore', () => ({
useAuthStore: () => ({
user: mockUser,
logout: mockLogout,
}),
}));
// Mock versionApi
jest.mock('@/lib/api', () => ({
versionApi: {
get: jest.fn(),
},
}));
const regularUser = {
id: 1,
email: 'user@example.com',
full_name: 'Regular User',
is_active: true,
is_superuser: false,
subscription_tier: 'free',
subscription_status: 'active',
created_at: '2024-01-01T00:00:00Z',
};
const adminUser = {
...regularUser,
id: 2,
email: 'admin@example.com',
full_name: 'Admin User',
is_superuser: true,
};
describe('DashboardLayout', () => {
beforeEach(() => {
jest.clearAllMocks();
mockPathname = '/dashboard';
mockUser = regularUser;
mockVersionInfo = null;
});
it('should render the InboxConverge branding', () => {
render(
<DashboardLayout>
<div>Content</div>
</DashboardLayout>
);
// Desktop sidebar has the branding
expect(screen.getAllByText('InboxConverge').length).toBeGreaterThan(0);
});
it('should render main navigation items', () => {
render(
<DashboardLayout>
<div>Content</div>
</DashboardLayout>
);
expect(screen.getAllByText('Dashboard').length).toBeGreaterThan(0);
expect(screen.getAllByText('Mail Accounts').length).toBeGreaterThan(0);
expect(screen.getAllByText('Notifications').length).toBeGreaterThan(0);
expect(screen.getAllByText('Mailbox Activity').length).toBeGreaterThan(0);
expect(screen.getAllByText('Settings').length).toBeGreaterThan(0);
});
it('should render children in main content area', () => {
render(
<DashboardLayout>
<div data-testid="page-content">Page Content</div>
</DashboardLayout>
);
expect(screen.getByTestId('page-content')).toBeInTheDocument();
expect(screen.getByText('Page Content')).toBeInTheDocument();
});
it('should display user info in the top bar', () => {
render(
<DashboardLayout>
<div>Content</div>
</DashboardLayout>
);
expect(screen.getByText('Regular User')).toBeInTheDocument();
expect(screen.getByText('user@example.com')).toBeInTheDocument();
});
it('should not show admin navigation for regular users', () => {
render(
<DashboardLayout>
<div>Content</div>
</DashboardLayout>
);
expect(screen.queryByText('Admin Overview')).not.toBeInTheDocument();
expect(screen.queryByText('Manage Users')).not.toBeInTheDocument();
expect(screen.queryByText('Manage Plans')).not.toBeInTheDocument();
expect(screen.queryByText('Activity Logs')).not.toBeInTheDocument();
});
it('should show admin navigation for superusers', () => {
mockUser = adminUser;
render(
<DashboardLayout>
<div>Content</div>
</DashboardLayout>
);
expect(screen.getAllByText('Admin Overview').length).toBeGreaterThan(0);
expect(screen.getAllByText('Manage Users').length).toBeGreaterThan(0);
expect(screen.getAllByText('Manage Plans').length).toBeGreaterThan(0);
expect(screen.getAllByText('Activity Logs').length).toBeGreaterThan(0);
});
it('should show Admin badge for superusers', () => {
mockUser = adminUser;
render(
<DashboardLayout>
<div>Content</div>
</DashboardLayout>
);
// The Admin badge has a specific class for styling
const adminBadges = screen.getAllByText('Admin');
const badge = adminBadges.find((el) => el.classList.contains('bg-purple-100'));
expect(badge).toBeInTheDocument();
});
it('should not show Admin badge for regular users', () => {
render(
<DashboardLayout>
<div>Content</div>
</DashboardLayout>
);
expect(screen.queryByText('Admin')).not.toBeInTheDocument();
});
it('should call logout and redirect on Logout button click', () => {
render(
<DashboardLayout>
<div>Content</div>
</DashboardLayout>
);
// Click the first Logout button (desktop sidebar)
const logoutButtons = screen.getAllByText('Logout');
fireEvent.click(logoutButtons[0]);
expect(mockLogout).toHaveBeenCalled();
expect(mockPush).toHaveBeenCalledWith('/login');
});
it('should display the current page title based on pathname', () => {
mockPathname = '/accounts';
render(
<DashboardLayout>
<div>Content</div>
</DashboardLayout>
);
// The top bar should show "Mail Accounts" as the h2 heading
const headings = screen.getAllByText('Mail Accounts');
// At least one should be a heading in the top bar
expect(headings.length).toBeGreaterThan(0);
});
it('should show version info in the footer when available', () => {
mockVersionInfo = { version: '1.2.3', build_date: '2024-06-15T12:00:00Z' };
render(
<DashboardLayout>
<div>Content</div>
</DashboardLayout>
);
expect(screen.getByText('v1.2.3')).toBeInTheDocument();
});
it('should not show version info when not available', () => {
mockVersionInfo = null;
render(
<DashboardLayout>
<div>Content</div>
</DashboardLayout>
);
expect(screen.queryByText(/^v\d/)).not.toBeInTheDocument();
});
it('should render footer links', () => {
render(
<DashboardLayout>
<div>Content</div>
</DashboardLayout>
);
expect(screen.getByText('Impressum')).toBeInTheDocument();
expect(screen.getByText('Datenschutz')).toBeInTheDocument();
});
it('should open mobile sidebar on menu button click', () => {
render(
<DashboardLayout>
<div>Content</div>
</DashboardLayout>
);
// The mobile menu button has a Menu icon
const menuButton = screen.getByTestId('icon-Menu').closest('button');
expect(menuButton).toBeInTheDocument();
fireEvent.click(menuButton!);
// After clicking, the close (X) button should appear
expect(screen.getByTestId('icon-X')).toBeInTheDocument();
});
});
@@ -0,0 +1,26 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { QueryProvider } from './QueryProvider';
describe('QueryProvider', () => {
it('should render children', () => {
render(
<QueryProvider>
<div data-testid="child">Hello</div>
</QueryProvider>
);
expect(screen.getByTestId('child')).toBeInTheDocument();
expect(screen.getByText('Hello')).toBeInTheDocument();
});
it('should render multiple children', () => {
render(
<QueryProvider>
<div data-testid="first">First</div>
<div data-testid="second">Second</div>
</QueryProvider>
);
expect(screen.getByTestId('first')).toBeInTheDocument();
expect(screen.getByTestId('second')).toBeInTheDocument();
});
});
+127
View File
@@ -0,0 +1,127 @@
/**
* Tests for the Axios API instance configuration — interceptors and
* default headers. We use jest.mock to stub axios.create so we can
* inspect the interceptor callbacks that api.ts registers.
*/
// Capture interceptor callbacks registered by api.ts
type InterceptorFn = (config: Record<string, unknown>) => unknown;
type ErrorFn = (error: unknown) => unknown;
let requestInterceptor: InterceptorFn | null = null;
let responseSuccessInterceptor: InterceptorFn | null = null;
let responseErrorInterceptor: ErrorFn | null = null;
const mockCreate = jest.fn();
const mockAxiosInstance = {
interceptors: {
request: {
use: jest.fn((fn: InterceptorFn) => {
requestInterceptor = fn;
}),
},
response: {
use: jest.fn((successFn: InterceptorFn, errorFn: ErrorFn) => {
responseSuccessInterceptor = successFn;
responseErrorInterceptor = errorFn;
}),
},
},
get: jest.fn(),
post: jest.fn(),
put: jest.fn(),
patch: jest.fn(),
delete: jest.fn(),
};
mockCreate.mockReturnValue(mockAxiosInstance);
jest.mock('axios', () => ({
__esModule: true,
default: {
create: mockCreate,
},
}));
// Force module initialization to capture interceptors
require('./api');
describe('API module setup', () => {
it('should create an axios instance with correct baseURL', () => {
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
baseURL: '/api/v1',
headers: expect.objectContaining({
'Content-Type': 'application/json',
}),
})
);
});
it('should register request and response interceptors', () => {
expect(mockAxiosInstance.interceptors.request.use).toHaveBeenCalled();
expect(mockAxiosInstance.interceptors.response.use).toHaveBeenCalled();
});
});
describe('Request interceptor', () => {
beforeEach(() => {
localStorage.clear();
});
it('should attach Authorization header when access_token exists', () => {
localStorage.setItem('access_token', 'test-jwt-token');
const config = { headers: {} as Record<string, string> };
const result = requestInterceptor!(config) as typeof config;
expect(result.headers.Authorization).toBe('Bearer test-jwt-token');
});
it('should not attach Authorization header when no token exists', () => {
const config = { headers: {} as Record<string, string> };
const result = requestInterceptor!(config) as typeof config;
expect(result.headers.Authorization).toBeUndefined();
});
});
describe('Response interceptor', () => {
beforeEach(() => {
localStorage.clear();
});
it('should pass through successful responses', () => {
const response = { data: { ok: true }, status: 200 };
const result = responseSuccessInterceptor!(response);
expect(result).toBe(response);
});
it('should clear auth state on 401', async () => {
localStorage.setItem('access_token', 'expired-token');
localStorage.setItem('user', '{"id":1}');
const error = { response: { status: 401 } };
await expect(responseErrorInterceptor!(error)).rejects.toBe(error);
expect(localStorage.getItem('access_token')).toBeNull();
expect(localStorage.getItem('user')).toBeNull();
});
it('should not clear auth state for non-401 errors', async () => {
localStorage.setItem('access_token', 'valid-token');
const error = { response: { status: 500 } };
await expect(responseErrorInterceptor!(error)).rejects.toBe(error);
expect(localStorage.getItem('access_token')).toBe('valid-token');
});
it('should reject with the error for non-401 errors', async () => {
const error = { response: { status: 403 } };
await expect(responseErrorInterceptor!(error)).rejects.toBe(error);
});
it('should handle errors without a response object', async () => {
const error = new Error('Network error');
await expect(responseErrorInterceptor!(error)).rejects.toBe(error);
});
});
+154
View File
@@ -0,0 +1,154 @@
import { parseUTC, formatRelative, formatDate, formatDuration } from './date-utils';
describe('parseUTC', () => {
it('should parse ISO string with Z suffix as UTC', () => {
const date = parseUTC('2024-01-15T10:30:00Z');
expect(date.toISOString()).toBe('2024-01-15T10:30:00.000Z');
});
it('should parse ISO string with positive timezone offset', () => {
const date = parseUTC('2024-01-15T12:30:00+02:00');
expect(date.toISOString()).toBe('2024-01-15T10:30:00.000Z');
});
it('should parse ISO string with negative timezone offset', () => {
const date = parseUTC('2024-01-15T05:30:00-05:00');
expect(date.toISOString()).toBe('2024-01-15T10:30:00.000Z');
});
it('should append Z to timezone-naive ISO string', () => {
const date = parseUTC('2024-01-15T10:30:00');
expect(date.toISOString()).toBe('2024-01-15T10:30:00.000Z');
});
it('should handle ISO string with milliseconds and Z', () => {
const date = parseUTC('2024-01-15T10:30:00.123Z');
expect(date.toISOString()).toBe('2024-01-15T10:30:00.123Z');
});
it('should handle ISO string with compact offset (no colon)', () => {
const date = parseUTC('2024-01-15T12:30:00+0200');
expect(date.toISOString()).toBe('2024-01-15T10:30:00.000Z');
});
});
describe('formatRelative', () => {
it('should return "Never" for undefined input', () => {
expect(formatRelative(undefined)).toBe('Never');
});
it('should return "Never" for null input', () => {
expect(formatRelative(null)).toBe('Never');
});
it('should return "Never" for empty string', () => {
expect(formatRelative('')).toBe('Never');
});
it('should return "Just now" for timestamps less than 1 minute ago', () => {
const now = new Date().toISOString();
expect(formatRelative(now)).toBe('Just now');
});
it('should return minutes ago for timestamps less than 1 hour ago', () => {
const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000).toISOString();
expect(formatRelative(fiveMinutesAgo)).toBe('5m ago');
});
it('should return hours ago for timestamps less than 1 day ago', () => {
const threeHoursAgo = new Date(Date.now() - 3 * 60 * 60 * 1000).toISOString();
expect(formatRelative(threeHoursAgo)).toBe('3h ago');
});
it('should return days ago for timestamps 1+ days ago', () => {
const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString();
expect(formatRelative(twoDaysAgo)).toBe('2d ago');
});
it('should return "1m ago" for exactly 1 minute ago', () => {
const oneMinuteAgo = new Date(Date.now() - 60 * 1000).toISOString();
expect(formatRelative(oneMinuteAgo)).toBe('1m ago');
});
it('should return "59m ago" for 59 minutes ago', () => {
const fiftyNineMinutesAgo = new Date(Date.now() - 59 * 60 * 1000).toISOString();
expect(formatRelative(fiftyNineMinutesAgo)).toBe('59m ago');
});
it('should return "1h ago" for exactly 60 minutes ago', () => {
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString();
expect(formatRelative(oneHourAgo)).toBe('1h ago');
});
it('should return "23h ago" for 23 hours ago', () => {
const twentyThreeHoursAgo = new Date(Date.now() - 23 * 60 * 60 * 1000).toISOString();
expect(formatRelative(twentyThreeHoursAgo)).toBe('23h ago');
});
it('should return "1d ago" for exactly 24 hours ago', () => {
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
expect(formatRelative(oneDayAgo)).toBe('1d ago');
});
it('should handle timezone-naive timestamps correctly', () => {
// Create a timestamp without Z suffix
const now = new Date();
const naive = now.toISOString().replace('Z', '');
// parseUTC will append Z, so it should be interpreted as UTC
const result = formatRelative(naive);
expect(result).toBe('Just now');
});
});
describe('formatDate', () => {
it('should return a locale-formatted date string', () => {
const result = formatDate('2024-01-15T10:30:00Z');
// The exact format depends on locale, but it should contain key parts
expect(typeof result).toBe('string');
expect(result.length).toBeGreaterThan(0);
});
it('should handle timezone-naive ISO strings', () => {
const result = formatDate('2024-01-15T10:30:00');
expect(typeof result).toBe('string');
expect(result.length).toBeGreaterThan(0);
});
});
describe('formatDuration', () => {
it('should return em dash for null', () => {
expect(formatDuration(null)).toBe('—');
});
it('should return em dash for undefined', () => {
expect(formatDuration(undefined)).toBe('—');
});
it('should format 0 seconds', () => {
expect(formatDuration(0)).toBe('0.0s');
});
it('should format sub-minute durations with one decimal', () => {
expect(formatDuration(3.14)).toBe('3.1s');
});
it('should format exactly 59.9 seconds', () => {
expect(formatDuration(59.9)).toBe('59.9s');
});
it('should format exactly 60 seconds as minutes', () => {
expect(formatDuration(60)).toBe('1m 0s');
});
it('should format 125 seconds as 2m 5s', () => {
expect(formatDuration(125)).toBe('2m 5s');
});
it('should format large durations', () => {
expect(formatDuration(3661)).toBe('61m 1s');
});
it('should format fractional seconds above 60', () => {
expect(formatDuration(65.7)).toBe('1m 5s');
});
});
+1
View File
@@ -0,0 +1 @@
import '@testing-library/jest-dom';