Skip to content
Draft
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
10 changes: 10 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = {
presets: [
'@babel/preset-env',
'@babel/preset-react',
'@babel/preset-typescript'
],
plugins: [
'@babel/plugin-transform-runtime'
]
};
94 changes: 94 additions & 0 deletions components/EmailLoginForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import React, { useState } from 'react';
import { Input } from './ui/input';
import { Button } from './ui/button';
import { Label } from './ui/label';
import { useToast } from './ui/use-toast';

interface EmailLoginFormProps {
onLogin: (email: string, password: string) => Promise<void>;
}

export const EmailLoginForm: React.FC<EmailLoginFormProps> = ({ onLogin }) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [isLoading, setIsLoading] = useState(false);
const { toast } = useToast();

const validateEmail = (email: string): boolean => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();

// Reset previous errors
if (!validateEmail(email)) {
toast({
title: 'Invalid Email',
description: 'Please enter a valid email address.',
variant: 'destructive',
});
return;
}

if (password.length < 6) {
toast({
title: 'Invalid Password',
description: 'Password must be at least 6 characters long.',
variant: 'destructive',
});
return;
}

setIsLoading(true);
try {
await onLogin(email, password);
} catch (error) {
toast({
title: 'Login Failed',
description: error instanceof Error ? error.message : 'An unexpected error occurred',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};

return (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="Enter your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
data-testid="email-input"
/>
</div>
<div>
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
placeholder="Enter your password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
data-testid="password-input"
/>
</div>
<Button
type="submit"
disabled={isLoading}
data-testid="login-button"
className="w-full"
>
{isLoading ? 'Logging in...' : 'Log In'}
</Button>
</form>
);
};
124 changes: 124 additions & 0 deletions components/__tests__/EmailLoginForm.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import '@testing-library/jest-dom';
import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { EmailLoginForm } from '../EmailLoginForm';
import { Toaster } from '../ui/toaster';

// Mock the useToast hook
const mockToast = jest.fn();
jest.mock('../ui/use-toast', () => ({
useToast: () => ({
toast: mockToast,
}),
}));

describe('EmailLoginForm', () => {
const mockOnLogin = jest.fn();

beforeEach(() => {
mockOnLogin.mockClear();
mockToast.mockClear();
});

it('renders email and password inputs', () => {
render(<EmailLoginForm onLogin={mockOnLogin} />);

expect(screen.getByTestId('email-input')).toBeInTheDocument();
expect(screen.getByTestId('password-input')).toBeInTheDocument();
expect(screen.getByTestId('login-button')).toBeInTheDocument();
});

it('validates email format', async () => {
render(<>
<EmailLoginForm onLogin={mockOnLogin} />
<Toaster />
</>);

const emailInput = screen.getByTestId('email-input');
const passwordInput = screen.getByTestId('password-input');
const loginButton = screen.getByTestId('login-button');

// Invalid email
fireEvent.change(emailInput, { target: { value: 'invalid-email' } });
fireEvent.change(passwordInput, { target: { value: 'password123' } });
fireEvent.click(loginButton);

await waitFor(() => {
expect(mockToast).toHaveBeenCalledWith(
expect.objectContaining({
title: 'Invalid Email',
})
);
expect(mockOnLogin).not.toHaveBeenCalled();
});
});

it('validates password length', async () => {
render(<>
<EmailLoginForm onLogin={mockOnLogin} />
<Toaster />
</>);

const emailInput = screen.getByTestId('email-input');
const passwordInput = screen.getByTestId('password-input');
const loginButton = screen.getByTestId('login-button');

// Invalid password
fireEvent.change(emailInput, { target: { value: '[email protected]' } });
fireEvent.change(passwordInput, { target: { value: '123' } });
fireEvent.click(loginButton);

await waitFor(() => {
expect(mockToast).toHaveBeenCalledWith(
expect.objectContaining({
title: 'Invalid Password',
})
);
expect(mockOnLogin).not.toHaveBeenCalled();
});
});

it('calls onLogin with correct credentials', async () => {
mockOnLogin.mockResolvedValue(undefined);

render(<EmailLoginForm onLogin={mockOnLogin} />);

const emailInput = screen.getByTestId('email-input');
const passwordInput = screen.getByTestId('password-input');
const loginButton = screen.getByTestId('login-button');

fireEvent.change(emailInput, { target: { value: '[email protected]' } });
fireEvent.change(passwordInput, { target: { value: 'password123' } });
fireEvent.click(loginButton);

await waitFor(() => {
expect(mockOnLogin).toHaveBeenCalledWith('[email protected]', 'password123');
});
});

it('handles login error', async () => {
const errorMessage = 'Login failed';
mockOnLogin.mockRejectedValue(new Error(errorMessage));

render(<>
<EmailLoginForm onLogin={mockOnLogin} />
<Toaster />
</>);

const emailInput = screen.getByTestId('email-input');
const passwordInput = screen.getByTestId('password-input');
const loginButton = screen.getByTestId('login-button');

fireEvent.change(emailInput, { target: { value: '[email protected]' } });
fireEvent.change(passwordInput, { target: { value: 'password123' } });
fireEvent.click(loginButton);

await waitFor(() => {
expect(mockToast).toHaveBeenCalledWith(
expect.objectContaining({
title: 'Login Failed',
})
);
});
});
});
16 changes: 16 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
setupFilesAfterEnv: [],
moduleNameMapper: {
'\\.(css|less|scss|sass)$': 'identity-obj-proxy',
'^@/(.*)$': '<rootDir>/$1'
},
transform: {
'^.+\\.(js|jsx|ts|tsx)$': 'babel-jest',
},
testMatch: [
'**/__tests__/**/*.+(ts|tsx|js)',
'**/?(*.)+(spec|test).+(ts|tsx|js)',
],
};
Loading