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

Text length counter fixed in ContactForm #1369

Merged
merged 4 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
215 changes: 215 additions & 0 deletions src/app/common/components/ContactForm/ContactForm.component.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
import {
cleanup, fireEvent, render, screen, waitFor,
} from '@testing-library/react';
import user from '@testing-library/user-event';

import EmailApi from '@/app/api/email/email.api';

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

import ContactForm from './ContactForm.component';

// needed to render component without errors
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: (query: unknown) => ({
matches: false,
media: query,
onchange: null,
addListener: () => {},
removeListener: () => {},
addEventListener: () => {},
removeEventListener: () => {},
dispatchEvent: () => {},
}),
});

// mock ReCAPTCHA component
const onCaptchaMock = jest.fn();
jest.mock('react-google-recaptcha', () => jest.fn(({ onChange }) => (
<div data-testid="mock-recaptcha">
<button
type="button"
onClick={() => {
if (onChange) onChange('mock-token');
onCaptchaMock();
}}
>
Verify ReCAPTCHA
</button>
</div>
)));

// mock backend api calls
jest.mock('@/app/api/email/email.api', () => ({
send: jest.fn(() => {}),
}));

describe('ContactForm test', () => {
afterEach(() => {
jest.clearAllMocks();
cleanup();
});

it('should be rendered', async () => {
render(
<ContactForm />,
);

const textareaMessage = screen.getByPlaceholderText(/Наші серця/i);
const inputEmail = screen.getByPlaceholderText(/E-mail/i);
const buttonSend = screen.getByText(/Відправити/i);

await waitFor(() => {
expect(textareaMessage).toBeInTheDocument();
expect(inputEmail).toBeInTheDocument();
expect(buttonSend).toBeInTheDocument();
});
});

it('should send Email with filled fields', async () => {
render(
<ContactForm />,
);

// Arrange
const textareaMessage = screen.getByPlaceholderText(/Наші серця/i) as HTMLTextAreaElement;
const inputEmail = screen.getByPlaceholderText(/E-mail/i) as HTMLInputElement;
const captchaButton = screen.getByText(/Verify ReCAPTCHA/i);
const sendButton = screen.getByText(/Відправити/i);

const message = 'Some interesting message';
const email = '[email protected]';

// Act
await waitFor(async () => {
user.type(inputEmail, email);
user.type(textareaMessage, message);
user.click(captchaButton);
user.click(sendButton);
});

// Assert
expect(textareaMessage.value).toBe(message);
expect(inputEmail.value).toBe(email);
expect(onCaptchaMock).toHaveBeenCalled();
expect(EmailApi.send).toHaveBeenCalled();
});

it('should not send Email with invalid email field', async () => {
render(
<ContactForm />,
);

// Arrange
const textareaMessage = screen.getByPlaceholderText(/Наші серця/i) as HTMLTextAreaElement;
const inputEmail = screen.getByPlaceholderText(/E-mail/i) as HTMLInputElement;
const captchaButton = screen.getByText(/Verify ReCAPTCHA/i);
const sendButton = screen.getByText(/Відправити/i);

const message = 'Some interesting message';
const email = 'invalid email';

// Act
await waitFor(async () => {
user.type(inputEmail, email);
user.type(textareaMessage, message);
user.click(captchaButton);
user.click(sendButton);
});

// Assert
expect(textareaMessage.value).toBe(message);
expect(inputEmail.value).toBe(email);
expect(onCaptchaMock).toHaveBeenCalled();
expect(EmailApi.send).not.toHaveBeenCalled();
});

it('should not send Email with epty message field', async () => {
render(
<ContactForm />,
);

// Arrange
const textareaMessage = screen.getByPlaceholderText(/Наші серця/i) as HTMLTextAreaElement;
const inputEmail = screen.getByPlaceholderText(/E-mail/i) as HTMLInputElement;
const captchaButton = screen.getByText(/Verify ReCAPTCHA/i);
const sendButton = screen.getByText(/Відправити/i);

const email = '[email protected]';

// Act
await waitFor(async () => {
user.type(inputEmail, email);
user.click(captchaButton);
user.click(sendButton);
});

// Assert
expect(textareaMessage.value).toBe('');
expect(inputEmail.value).toBe(email);
expect(onCaptchaMock).toHaveBeenCalled();
expect(EmailApi.send).not.toHaveBeenCalled();
});

it('should not send Email without ReCAPTCHA', async () => {
render(
<ContactForm />,
);

// Arrange
const textareaMessage = screen.getByPlaceholderText(/Наші серця/i) as HTMLTextAreaElement;
const inputEmail = screen.getByPlaceholderText(/E-mail/i) as HTMLInputElement;
const sendButton = screen.getByText(/Відправити/i);

const message = 'Some interesting message';
const email = '[email protected]';

// Act
await waitFor(async () => {
user.type(inputEmail, email);
user.type(textareaMessage, message);
user.click(sendButton);
});

// Assert
expect(inputEmail.value).toBe(email);
expect(textareaMessage.value).toBe(message);
expect(onCaptchaMock).not.toHaveBeenCalled();
expect(EmailApi.send).not.toHaveBeenCalled();
});

it('should check text amount restrictions and Email validation', async () => {
render(
<ContactForm />,
);

// Arrange
const textareaMessage = screen.getByPlaceholderText(/Наші серця/i) as HTMLTextAreaElement;
const inputEmail = screen.getByPlaceholderText(/E-mail/i);
const buttonSend = screen.getByText(/Відправити/i);

const descriptionRestriction = 500;
const invalidEmail = '[email protected]';
const text = 'String which excides text amount limit';
const veryLongText = text.repeat(13);

// Act
await waitFor(async () => {
user.type(inputEmail, invalidEmail);

// user.type() takes too much time to input all the text, so fireEvent.change() partially
// fills description and user.type() tries to exceed text amount restrictions\
fireEvent.change(textareaMessage, { target: { value: veryLongText } });
user.type(textareaMessage, text);

user.click(buttonSend);
});

// Assert
const validationMessage = await screen.findByText(/E-mail може містити/i);
expect(validationMessage).toBeInTheDocument();
expect(textareaMessage.value.length).toBe(descriptionRestriction);
expect(EmailApi.send).not.toHaveBeenCalled();
});
});
42 changes: 21 additions & 21 deletions src/app/common/components/ContactForm/ContactForm.component.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import './ContactForm.styles.scss';

import { LegacyRef, forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';

import { Button, Form, Input, message } from 'antd';

import EmailApi from '@/app/api/email/email.api';
import Email from '@/models/email/email.model';

import { ERROR_MESSAGES } from '../../constants/error-messages.constants';

const MAX_SYMBOLS = 500;
Expand Down Expand Up @@ -40,44 +41,42 @@ const ContactForm = forwardRef((customClass: Props, ref) => {
},
}));

const successMessage = () => {
messageApi.open({
type: 'success',
content: 'Лист успішно надісланий',
});
};

const errorMessage = (error: string) => {
messageApi.open({
type: 'error',
content: error,
});
};

const onFinish = () => {
if (isVerified) {
const token = recaptchaRef?.current?.getValue();
const newEmail: Email = { from: formData.email, content: formData.message, token: token };
const newEmail: Email = { from: formData.email, content: formData.message, token };
EmailApi.send(newEmail)
.then(() => {
successMessage();
})
.catch((error) => {
if (error === 429) {
errorMessage(MESSAGE_LIMIT);
}
else {
} else {
errorMessage(SOMETHING_IS_WRONG);
}
});
recaptchaRef.current?.reset();
setIsVerified(false);
}
else {
} else {
errorMessage(RECAPTCHA_CHECK);
}
};

const successMessage = () => {
messageApi.open({
type: 'success',
content: 'Лист успішно надісланий',
});
};

const errorMessage = (message: string) => {
messageApi.open({
type: 'error',
content: message,
});
};

return (
<div className={`formWrapper ${customClass}`}>
{messageContextHolder}
Expand Down Expand Up @@ -109,6 +108,7 @@ const ContactForm = forwardRef((customClass: Props, ref) => {
name="message"
autoSize={{ minRows: 4, maxRows: 4 }}
placeholder="Наші серця, очі та вуха відкриті до твоїх креативних повідомлень!"
showCount
maxLength={MAX_SYMBOLS}
onChange={handleChange}
/>
Expand All @@ -135,7 +135,7 @@ const ContactForm = forwardRef((customClass: Props, ref) => {
<div className="captchaBlock">
<ReCAPTCHA
className="required-captcha"
sitekey={siteKey ? siteKey : ""}
sitekey={siteKey || ''}
onChange={handleVerify}
onExpired={handleExpiration}
ref={recaptchaRef}
Expand Down
Loading
Loading