Fix all tests and replace enzyme with @testing-library/react

This commit is contained in:
SleepWalker
2020-05-21 21:08:47 +03:00
parent a0ec9574e2
commit e1f15b5d22
20 changed files with 430 additions and 600 deletions

View File

@@ -124,7 +124,7 @@ describe('components/auth/actions', () => {
return callThunk(oAuthComplete).then(() => {
expect(request.post, 'to have a call satisfying', [
'/api/oauth2/v1/complete?client_id=&redirect_uri=&response_type=&description=&scope=&prompt=&login_hint=&state=',
'/api/oauth2/v1/complete?client_id=&redirect_uri=&response_type=&description=&scope=&prompt=none&login_hint=&state=',
{},
]);
});

View File

@@ -1,61 +1,60 @@
import React, { ComponentProps } from 'react';
import React from 'react';
import expect from 'app/test/unexpected';
import sinon from 'sinon';
import { shallow, mount, ShallowWrapper, ReactWrapper } from 'enzyme';
import { IntlProvider } from 'react-intl';
import { render, fireEvent, waitFor, screen } from '@testing-library/react';
import feedback from 'app/services/api/feedback';
import { User } from 'app/components/user';
import { TestContextProvider } from 'app/shell';
import { ContactForm } from './ContactForm';
type ContactFormShallowType = ShallowWrapper<
ComponentProps<typeof ContactForm>,
any,
ContactForm
>;
beforeEach(() => {
sinon.stub(feedback, 'send').returns(Promise.resolve() as any);
});
afterEach(() => {
(feedback.send as any).restore();
});
describe('ContactForm', () => {
describe('when rendered', () => {
it('should contain Form', () => {
const user = {} as User;
let component: ContactFormShallowType;
beforeEach(() => {
component = shallow(<ContactForm user={user} />);
});
render(
<TestContextProvider>
<ContactForm user={user} />
</TestContextProvider>,
);
expect(screen.getAllByRole('textbox').length, 'to be greater than', 1);
expect(
screen.getByRole('button', { name: /Send/ }),
'to have property',
'type',
'submit',
);
[
{
type: 'Input',
label: 'subject',
name: 'subject',
},
{
type: 'Input',
label: 'Email',
name: 'email',
},
{
type: 'Dropdown',
name: 'category',
},
{
type: 'TextArea',
label: 'message',
name: 'message',
},
].forEach((el) => {
it(`should have ${el.name} field`, () => {
expect(component.find(`${el.type}[name="${el.name}"]`), 'to satisfy', {
length: 1,
});
});
});
it('should contain Form', () => {
expect(component.find('Form'), 'to satisfy', { length: 1 });
});
it('should contain submit Button', () => {
expect(component.find('Button[type="submit"]'), 'to satisfy', {
length: 1,
});
expect(
screen.getByLabelText(el.label, { exact: false }),
'to have property',
'name',
el.name,
);
});
});
@@ -63,148 +62,109 @@ describe('ContactForm', () => {
const user = {
email: 'foo@bar.com',
} as User;
let component: ContactFormShallowType;
beforeEach(() => {
component = shallow(<ContactForm user={user} />);
});
it('should render email field with user email', () => {
render(
<TestContextProvider>
<ContactForm user={user} />
</TestContextProvider>,
);
expect(screen.getByDisplayValue(user.email), 'to be a', HTMLInputElement);
});
});
it('should submit and then hide form and display success message', async () => {
const user = {
email: 'foo@bar.com',
} as User;
render(
<TestContextProvider>
<ContactForm user={user} />
</TestContextProvider>,
);
fireEvent.change(screen.getByLabelText(/subject/i), {
target: {
value: 'subject',
},
});
fireEvent.change(screen.getByLabelText(/message/i), {
target: {
value: 'the message',
},
});
const button = screen.getByRole('button', { name: 'Send' });
expect(button, 'to have property', 'disabled', false);
fireEvent.click(button);
expect(button, 'to have property', 'disabled', true);
expect(feedback.send, 'to have a call exhaustively satisfying', [
{
subject: 'subject',
email: user.email,
category: '',
message: 'the message',
},
]);
await waitFor(() => {
expect(
component.find('Input[name="email"]').prop('defaultValue'),
'to equal',
user.email,
screen.getByText('Your message was received', { exact: false }),
'to be a',
HTMLElement,
);
});
expect(screen.getByText(user.email), 'to be a', HTMLElement);
expect(screen.queryByRole('button', { name: /Send/ }), 'to be null');
});
describe('when email was successfully sent', () => {
it('should show validation messages', async () => {
const user = {
email: 'foo@bar.com',
} as User;
let component: ContactFormShallowType;
beforeEach(() => {
component = shallow(<ContactForm user={user} />);
(feedback.send as any).callsFake(() =>
Promise.reject({
success: false,
errors: { email: 'error.email_invalid' },
}),
);
component.setState({ isSuccessfullySent: true });
render(
<TestContextProvider>
<ContactForm user={user} />
</TestContextProvider>,
);
fireEvent.change(screen.getByLabelText(/subject/i), {
target: {
value: 'subject',
},
});
it('should not contain Form', () => {
expect(component.find('Form'), 'to satisfy', { length: 0 });
fireEvent.change(screen.getByLabelText(/message/i), {
target: {
value: 'the message',
},
});
});
xdescribe('validation', () => {
const user = {
email: 'foo@bar.com',
} as User;
let component: ContactForm;
let wrapper: ReactWrapper;
fireEvent.click(screen.getByRole('button', { name: 'Send' }));
beforeEach(() => {
// TODO: add polyfill for from validation for jsdom
wrapper = mount(
<IntlProvider locale="en" defaultLocale="en">
<ContactForm user={user} ref={(el) => (component = el!)} />
</IntlProvider>,
await waitFor(() => {
expect(
screen.getByRole('alert'),
'to have property',
'innerHTML',
'Email is invalid',
);
});
it('should require email, subject and message', () => {
// wrapper.find('[type="submit"]').simulate('click');
wrapper.find('form').simulate('submit');
expect(component.form.hasErrors(), 'to be true');
});
});
describe('when user submits form', () => {
const user = {
email: 'foo@bar.com',
} as User;
let component: ContactForm;
let wrapper: ReactWrapper;
const requestData = {
email: user.email,
subject: 'Test subject',
message: 'Test message',
};
beforeEach(() => {
sinon.stub(feedback, 'send');
// TODO: add polyfill for from validation for jsdom
if (!(Element.prototype as any).checkValidity) {
(Element.prototype as any).checkValidity = () => true;
}
// TODO: try to rewrite with unexpected-react
wrapper = mount(
<IntlProvider locale="en" defaultLocale="en">
<ContactForm user={user} ref={(el) => (component = el!)} />
</IntlProvider>,
);
wrapper.find('input[name="email"]').getDOMNode<HTMLInputElement>().value =
requestData.email;
wrapper
.find('input[name="subject"]')
.getDOMNode<HTMLInputElement>().value = requestData.subject;
wrapper
.find('textarea[name="message"]')
.getDOMNode<HTMLInputElement>().value = requestData.message;
});
afterEach(() => {
(feedback.send as any).restore();
});
xit('should call onSubmit', () => {
sinon.stub(component, 'onSubmit');
wrapper.find('form').simulate('submit');
expect(component.onSubmit, 'was called');
});
it('should call send with required data', () => {
(feedback.send as any).returns(Promise.resolve());
component.onSubmit();
expect(feedback.send, 'to have a call satisfying', [requestData]);
});
it('should set isSuccessfullySent', () => {
(feedback.send as any).returns(Promise.resolve());
return component
.onSubmit()
.then(() =>
expect(component.state, 'to satisfy', { isSuccessfullySent: true }),
);
});
it('should handle isLoading during request', () => {
(feedback.send as any).returns(Promise.resolve());
const promise = component.onSubmit();
expect(component.state, 'to satisfy', { isLoading: true });
return promise.then(() =>
expect(component.state, 'to satisfy', { isLoading: false }),
);
});
it('should render success message with user email', () => {
(feedback.send as any).returns(Promise.resolve());
return component
.onSubmit()
.then(() => expect(wrapper.text(), 'to contain', user.email));
});
});
});

View File

@@ -140,7 +140,12 @@ export class ContactForm extends React.Component<
</div>
<div className={styles.footer}>
<Button label={messages.send} block type="submit" />
<Button
label={messages.send}
block
type="submit"
disabled={isLoading}
/>
</div>
</Form>
);

View File

@@ -11,6 +11,11 @@ const IntlProvider: ComponentType = ({ children }) => {
);
useEffect(() => {
if (process.env.NODE_ENV === 'test') {
// disable async modules loading in tests
return;
}
(async () => {
setIntl(await i18n.changeLocale(locale));
})();

View File

@@ -1,25 +1,57 @@
import React from 'react';
import expect from 'app/test/unexpected';
import uxpect from 'app/test/unexpected';
import { render, fireEvent, screen } from '@testing-library/react';
import sinon from 'sinon';
import { TestContextProvider } from 'app/shell';
import { shallow } from 'enzyme';
import ChangePassword from 'app/components/profile/changePassword/ChangePassword';
import ChangePassword from './ChangePassword';
describe('<ChangePassword />', () => {
it('renders two <Input /> components', () => {
const component = shallow(<ChangePassword onSubmit={async () => {}} />);
render(
<TestContextProvider>
<ChangePassword onSubmit={async () => {}} />
</TestContextProvider>,
);
expect(component.find('Input'), 'to satisfy', { length: 2 });
expect(
screen.getByLabelText('New password', { exact: false }),
).toBeInTheDocument();
expect(
screen.getByLabelText('Repeat the password', { exact: false }),
).toBeInTheDocument();
});
it('should call onSubmit if passwords entered', () => {
const onSubmit = sinon.spy(() => ({ catch: () => {} })).named('onSubmit');
// @ts-ignore
const component = shallow(<ChangePassword onSubmit={onSubmit} />);
it('should call onSubmit if passwords entered', async () => {
const onSubmit = sinon.spy(() => Promise.resolve()).named('onSubmit');
component.find('Form').simulate('submit');
render(
<TestContextProvider>
<ChangePassword onSubmit={onSubmit} />
</TestContextProvider>,
);
expect(onSubmit, 'was called');
fireEvent.change(screen.getByLabelText('New password', { exact: false }), {
target: {
value: '123',
},
});
fireEvent.change(
screen.getByLabelText('Repeat the password', { exact: false }),
{
target: {
value: '123',
},
},
);
fireEvent.click(
screen
.getByRole('button', { name: 'Change password' })
.closest('button') as HTMLButtonElement,
);
uxpect(onSubmit, 'was called');
});
});

View File

@@ -30,7 +30,11 @@ const FormError: ComponentType<Props> = ({ error }) => {
content = resolveError(error);
}
return <div className={styles.fieldError}>{content}</div>;
return (
<div className={styles.fieldError} role="alert">
{content}
</div>
);
};
export default FormError;

View File

@@ -1,5 +1,5 @@
import React from 'react';
import { mount } from 'enzyme';
import { render, screen } from '@testing-library/react';
import expect from 'app/test/unexpected';
import { IntlProvider } from 'react-intl';
@@ -7,9 +7,9 @@ import Input from './Input';
describe('Input', () => {
it('should return input value', () => {
let component: any;
let component: Input | null = null;
const wrapper = mount(
render(
<IntlProvider locale="en" defaultLocale="en">
<Input
defaultValue="foo"
@@ -21,11 +21,7 @@ describe('Input', () => {
</IntlProvider>,
);
expect(
wrapper.find('input[name="test"]').getDOMNode<HTMLInputElement>().value,
'to equal',
'foo',
);
expect(component.getValue(), 'to equal', 'foo');
expect(screen.getByDisplayValue('foo'), 'to be a', HTMLElement);
expect(component && (component as Input).getValue(), 'to equal', 'foo');
});
});

View File

@@ -1,15 +1,18 @@
import sinon from 'sinon';
import expect from 'app/test/unexpected';
import uxpect from 'app/test/unexpected';
import { render, fireEvent, waitFor, screen } from '@testing-library/react';
import React from 'react';
import { shallow, mount } from 'enzyme';
import { PopupStack } from './PopupStack';
import PopupStack from 'app/components/ui/popup/PopupStack';
import styles from 'app/components/ui/popup/popup.scss';
function DummyPopup(_props: Record<string, any>) {
return null;
function DummyPopup({ onClose }: Record<string, any>) {
return (
<div>
<button type="button" onClick={onClose}>
close
</button>
</div>
);
}
describe('<PopupStack />', () => {
@@ -25,60 +28,42 @@ describe('<PopupStack />', () => {
},
],
};
const component = shallow(<PopupStack {...props} />);
expect(component.find(DummyPopup), 'to satisfy', { length: 2 });
render(<PopupStack {...props} />);
const popups = screen.getAllByRole('dialog');
uxpect(popups, 'to have length', 2);
});
it('should pass onClose as props', () => {
const expectedProps = {
foo: 'bar',
};
const props: any = {
destroy: () => {},
popups: [
{
Popup: (popupProps = { onClose: Function }) => {
// eslint-disable-next-line
expect(popupProps.onClose, 'to be a', 'function');
return <DummyPopup {...expectedProps} />;
},
},
],
};
const component = mount(<PopupStack {...props} />);
const popup = component.find(DummyPopup);
expect(popup, 'to satisfy', { length: 1 });
expect(popup.props(), 'to equal', expectedProps);
});
it('should hide popup, when onClose called', () => {
it('should hide popup, when onClose called', async () => {
const destroy = sinon.stub().named('props.destroy');
const props: any = {
popups: [
{
Popup: DummyPopup,
},
{
Popup: DummyPopup,
},
],
destroy: sinon.stub().named('props.destroy'),
destroy,
};
const component = shallow(<PopupStack {...props} />);
component.find(DummyPopup).last().prop('onClose')();
const { rerender } = render(<PopupStack {...props} />);
expect(props.destroy, 'was called once');
expect(props.destroy, 'to have a call satisfying', [
expect.it('to be', props.popups[1]),
fireEvent.click(screen.getByRole('button', { name: 'close' }));
uxpect(destroy, 'was called once');
uxpect(destroy, 'to have a call satisfying', [
uxpect.it('to be', props.popups[0]),
]);
rerender(<PopupStack popups={[]} destroy={destroy} />);
await waitFor(() => {
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
});
it('should hide popup, when overlay clicked', () => {
const preventDefault = sinon.stub().named('event.preventDefault');
const props: any = {
destroy: sinon.stub().named('props.destroy'),
popups: [
@@ -87,16 +72,15 @@ describe('<PopupStack />', () => {
},
],
};
const component = shallow(<PopupStack {...props} />);
const overlay = component.find(`.${styles.overlay}`);
overlay.simulate('click', { target: 1, currentTarget: 1, preventDefault });
render(<PopupStack {...props} />);
expect(props.destroy, 'was called once');
expect(preventDefault, 'was called once');
fireEvent.click(screen.getByRole('dialog'));
uxpect(props.destroy, 'was called once');
});
it('should hide popup on overlay click if disableOverlayClose', () => {
it('should not hide popup on overlay click if disableOverlayClose', () => {
const props: any = {
destroy: sinon.stub().named('props.destroy'),
popups: [
@@ -106,16 +90,12 @@ describe('<PopupStack />', () => {
},
],
};
const component = shallow(<PopupStack {...props} />);
const overlay = component.find(`.${styles.overlay}`);
overlay.simulate('click', {
target: 1,
currentTarget: 1,
preventDefault() {},
});
render(<PopupStack {...props} />);
expect(props.destroy, 'was not called');
fireEvent.click(screen.getByRole('dialog'));
uxpect(props.destroy, 'was not called');
});
it('should hide popup, when esc pressed', () => {
@@ -127,14 +107,15 @@ describe('<PopupStack />', () => {
},
],
};
mount(<PopupStack {...props} />);
render(<PopupStack {...props} />);
const event = new Event('keyup');
// @ts-ignore
event.which = 27;
document.dispatchEvent(event);
expect(props.destroy, 'was called once');
uxpect(props.destroy, 'was called once');
});
it('should hide first popup in stack if esc pressed', () => {
@@ -151,16 +132,17 @@ describe('<PopupStack />', () => {
},
],
};
mount(<PopupStack {...props} />);
render(<PopupStack {...props} />);
const event = new Event('keyup');
// @ts-ignore
event.which = 27;
document.dispatchEvent(event);
expect(props.destroy, 'was called once');
expect(props.destroy, 'to have a call satisfying', [
expect.it('to be', props.popups[1]),
uxpect(props.destroy, 'was called once');
uxpect(props.destroy, 'to have a call satisfying', [
uxpect.it('to be', props.popups[1]),
]);
});
@@ -174,13 +156,14 @@ describe('<PopupStack />', () => {
},
],
};
mount(<PopupStack {...props} />);
render(<PopupStack {...props} />);
const event = new Event('keyup');
// @ts-ignore
event.which = 27;
document.dispatchEvent(event);
expect(props.destroy, 'was not called');
uxpect(props.destroy, 'was not called');
});
});

View File

@@ -48,6 +48,7 @@ export class PopupStack extends React.Component<Props> {
>
<div
className={styles.overlay}
role="dialog"
onClick={this.onOverlayClick(popup)}
>
<Popup onClose={this.onClose(popup)} />
@@ -60,7 +61,7 @@ export class PopupStack extends React.Component<Props> {
}
onClose(popup: PopupConfig) {
return this.props.destroy.bind(null, popup);
return () => this.props.destroy(popup);
}
onOverlayClick(popup: PopupConfig) {