Skip to content

Instantly share code, notes, and snippets.

@hjumeau
Last active January 12, 2020 08:42
Show Gist options
  • Save hjumeau/872402ba05f9c99d8d25fae53c604ebc to your computer and use it in GitHub Desktop.
Save hjumeau/872402ba05f9c99d8d25fae53c604ebc to your computer and use it in GitHub Desktop.
A test of a login redux-form with enzyme+mount
import React from 'react';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { mountWithProviders } from '../../../../helpers/test';
import { LoginForm } from './LoginForm';
configure({ adapter: new Adapter() });
describe('LoginForm Component', () => {
it('should show username label', () => {
// WHEN
const signInFormElement = mountWithProviders(<LoginForm />);
const usernameLabelElement = signInFormElement.find('[data-testid="label-username"]');
// THEN
expect(usernameLabelElement.text()).toEqual('USERNAME');
});
it('should show password label', () => {
// WHEN
const signInFormElement = mountWithProviders(<LoginForm />);
const passwordLabelElement = signInFormElement.find('[data-testid="label-password"]');
// THEN
expect(passwordLabelElement.text()).toEqual('PASSWORD');
});
it('should submit the username and password', () => {
// GIVEN
const onSubmitMock = jest.fn();
const password = 'test';
const username = '[email protected]';
// WHEN
const signInFormElement = mountWithProviders(<LoginForm onSubmit={onSubmitMock}/>);
const passwordInput = signInFormElement.find('[data-testid="input-password"]');
const usernameInput = signInFormElement.find('[data-testid="input-username"]');
const signInSubmitButton = signInFormElement.find('[data-testid="button-sign-in-submit"]');
passwordInput.simulate('change', { target: { value: password } });
usernameInput.simulate('change', { target: { value: username } });
signInSubmitButton.simulate('submit');
// 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 signInFormElement = mountWithProviders(<LoginForm errorMessage={errorMsg} onSubmit={onSubmitMock}/>);
const errorMessageElement = signInFormElement.find('[data-testid="error-message"]');
// THEN
expect(errorMessageElement.text()).toEqual(errorMsg);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment