Skip to content

Instantly share code, notes, and snippets.

@hjumeau
Last active January 12, 2020 09:00
Show Gist options
  • Save hjumeau/e975621a49bbb6eec7c0d211dc9830e9 to your computer and use it in GitHub Desktop.
Save hjumeau/e975621a49bbb6eec7c0d211dc9830e9 to your computer and use it in GitHub Desktop.
Test of a login redux-form with react-testing-library
import React from 'react';
import { fireEvent } from '@testing-library/react';
import { renderWithProviders } from '../../../../helpers/test';
import { LoginForm } from './LoginForm';
describe('LoginForm Component', () => {
it('should submit the username and password', () => {
// GIVEN
const onSubmitMock = jest.fn();
const password = 'test';
const username = '[email protected]';
// WHEN
const {getByLabelText, getByText} = renderWithProviders(<LoginForm onSubmit={onSubmitMock}/>);
fireEvent.change(getByLabelText(/Username/i), {target: {value: username}});
fireEvent.change(getByLabelText(/Password/i), {target: {value: password}});
fireEvent.click(getByText('Connexion'));
// THEN
/*
onSubmit will be called with 3 parameters but only the first one interests me:
values : Object
The field values in the form of { field1: 'value1', field2: 'value2' }.
https://redux-form.com/8.2.2/docs/api/reduxform.md/#-code-onsubmit-function-code-optional-
a less explicite option:
expect(onSubmitMock.mock.calls[0][0]).toEqual({username, password});
*/
expect(onSubmitMock).toHaveBeenCalledWith(
{username, password},
expect.any(Function),
expect.any(Object),
);
});
it('should show a errorMessage message if passed one', () => {
// GIVEN
const onSubmitMock = jest.fn();
const errorMsg = 'errorMessage message';
// WHEN
const {getByText} = renderWithProviders(<LoginForm errorMessage={errorMsg} onSubmit={onSubmitMock}/>);
// THEN
expect(getByText(errorMsg)).not.toBeNull();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment