Refactor to enforce AuthContext usage over useAuthStore and improve test stability

- Replaced `useAuthStore` with `useAuth` from `AuthContext` across frontend components and tests to ensure dependency injection compliance.
- Enhanced E2E test stability by delaying navigation until the auth context is fully initialized.
- Updated Playwright configuration to use a single worker to prevent mock conflicts.
- Refactored test setup to consistently inject `AuthProvider` for improved isolation and mocking.
- Adjusted comments and documentation to clarify dependency injection and testability patterns.
This commit is contained in:
Felipe Cardoso
2025-11-05 08:37:01 +01:00
parent 7c98ceb5b9
commit f23fdb974a
14 changed files with 160 additions and 80 deletions

View File

@@ -5,6 +5,7 @@
import { render, waitFor } from '@testing-library/react';
import { AuthInitializer } from '@/components/auth/AuthInitializer';
import { AuthProvider } from '@/lib/auth/AuthContext';
import { useAuthStore } from '@/lib/stores/authStore';
// Mock the auth store
@@ -28,13 +29,21 @@ describe('AuthInitializer', () => {
describe('Initialization', () => {
it('renders nothing (null)', () => {
const { container } = render(<AuthInitializer />);
const { container } = render(
<AuthProvider>
<AuthInitializer />
</AuthProvider>
);
expect(container.firstChild).toBeNull();
});
it('calls loadAuthFromStorage on mount', async () => {
render(<AuthInitializer />);
render(
<AuthProvider>
<AuthInitializer />
</AuthProvider>
);
await waitFor(() => {
expect(mockLoadAuthFromStorage).toHaveBeenCalledTimes(1);
@@ -42,14 +51,22 @@ describe('AuthInitializer', () => {
});
it('does not call loadAuthFromStorage again on re-render', async () => {
const { rerender } = render(<AuthInitializer />);
const { rerender } = render(
<AuthProvider>
<AuthInitializer />
</AuthProvider>
);
await waitFor(() => {
expect(mockLoadAuthFromStorage).toHaveBeenCalledTimes(1);
});
// Force re-render
rerender(<AuthInitializer />);
rerender(
<AuthProvider>
<AuthInitializer />
</AuthProvider>
);
// Should still only be called once (useEffect dependencies prevent re-call)
expect(mockLoadAuthFromStorage).toHaveBeenCalledTimes(1);

View File

@@ -7,6 +7,7 @@ import { renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useUpdateProfile } from '@/lib/api/hooks/useUser';
import { useAuthStore } from '@/lib/stores/authStore';
import { AuthProvider } from '@/lib/auth/AuthContext';
import * as apiClient from '@/lib/api/client';
// Mock dependencies
@@ -32,7 +33,9 @@ describe('useUser hooks', () => {
const wrapper = ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>
{children}
<AuthProvider>
{children}
</AuthProvider>
</QueryClientProvider>
);