diff --git a/context/AuthContextProvider.test.tsx b/context/AuthContextProvider.test.tsx new file mode 100644 index 00000000..3684e783 --- /dev/null +++ b/context/AuthContextProvider.test.tsx @@ -0,0 +1,44 @@ +import React from 'react'; +import Alert from '@/components/AlertNotification/AlertNotification'; +import { AlertVariants } from '@/components/AlertNotification/Alerts.enum'; +import { render } from '@testing-library/react'; +import { toast } from 'react-hot-toast'; +import { logoutAccount } from './__mocks__/authcontextprovider'; + +const mockLoginAccount = jest.fn(); + +jest.mock('./AuthHelper', () => ({ + logoutAccount: logoutAccount, +})); + +describe('AuthContextProvider', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + test('mock a successful login and show default notification', async () => { + mockLoginAccount.mockResolvedValueOnce('default'); + + const result = await mockLoginAccount(); + expect(result).toBe('success'); + + const message = "You've successfully logged in!"; + const { getByText } = render( + , + ); + expect(getByText(message)).toBeInTheDocument(); + }); + + test('mock a failed login attempt and show error notification', async () => { + mockLoginAccount.mockRejectedValueOnce('error'); + + const result = await mockLoginAccount(); + expect(result).toBe('error'); + + const message = 'Something went wrong!'; + const { getByText } = render( + , + ); + expect(getByText(message)).toBeInTheDocument(); + }); +}); diff --git a/context/AuthContextProvider.tsx b/context/AuthContextProvider.tsx index fe49cbbf..598ecbf8 100644 --- a/context/AuthContextProvider.tsx +++ b/context/AuthContextProvider.tsx @@ -84,6 +84,12 @@ export const AuthContextProvider = ({ ); router.push('/login'); } catch (error) { + toast.custom( + , + ); console.error('Logout error:', error); } }; diff --git a/context/__mocks__/authcontextprovider.js b/context/__mocks__/authcontextprovider.js new file mode 100644 index 00000000..849856ac --- /dev/null +++ b/context/__mocks__/authcontextprovider.js @@ -0,0 +1,25 @@ +/** + * Log out and clear session state + * @returns {Promise} + */ +const logoutAccount = async (): Promise => { + try { + await account.deleteSession('current'); + setIsSignedIn(false); + resetUser(); // Reset user data in the store + toast.custom( + , + ); + router.push('/login'); + } catch (error) { + toast.custom( + , + ); + console.error('Logout error:', error); + } +}; + +export { logoutAccount };