Skip to content

Instantly share code, notes, and snippets.

@albertBarsegyan
Last active September 2, 2021 14:00
Show Gist options
  • Save albertBarsegyan/01829dfe284fcdff90ae972bae157af0 to your computer and use it in GitHub Desktop.
Save albertBarsegyan/01829dfe284fcdff90ae972bae157af0 to your computer and use it in GitHub Desktop.
Form testing
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import formTestConstants from '../../constants/formTest.constants';
import { CompanyForm } from '../../components/forms/CompanyForm/CompanyForm';
// testing if company form is working
describe('CompanyForm tests 🙂', () => {
it('Success test', async () => {
const handleSubmit = jest.fn();
const formComponent = render(<CompanyForm onSubmit={handleSubmit} />);
const priceName = formComponent.getByTestId('priceName');
const pricePhone = formComponent.getByTestId('pricePhone');
const priceEmail = formComponent.getByTestId('priceEmail');
const priceAgreement = formComponent.getByTestId('priceAgreement');
const submitButton = formComponent.getByTestId('companyFormSubmitButton');
userEvent.type(priceName, formTestConstants.testName);
userEvent.type(pricePhone, formTestConstants.testPhone);
userEvent.type(priceEmail, formTestConstants.testEmail);
userEvent.click(priceAgreement);
userEvent.click(submitButton);
await waitFor(() =>
expect(handleSubmit).toHaveBeenCalledWith({
agreement: formTestConstants.testAgreement,
email: formTestConstants.testEmail,
name: formTestConstants.testName,
phone: formTestConstants.testPhoneExpect,
}),
);
});
it('Failure test', async () => {
const handleSubmit = jest.fn();
render(<CompanyForm onSubmit={handleSubmit} />);
const submitButton = screen.getByTestId('companyFormSubmitButton');
const nameError = screen.getByTestId('nameError');
const emailError = screen.queryByTestId('emailError');
const phoneNumberError = screen.queryByTestId('phoneNumberError');
const agreementError = screen.queryByTestId('agreementError');
userEvent.click(submitButton);
// all inputs are empty
// it means every input and checkbox will show error message
await waitFor(() => {
expect(emailError.textContent).toMatch(
formTestConstants.errorMessageForEmail,
);
expect(nameError.textContent).toMatch(
formTestConstants.errorMessageForName,
);
expect(phoneNumberError.textContent).toMatch(
formTestConstants.errorMessageForPhone,
);
expect(agreementError.textContent).toMatch(
formTestConstants.errorMessageForAgreement,
);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment