Это должно помочь вам начать:
import * as React from 'react';
import { shallow } from 'enzyme';
let sendEmail = () => {};
class EmailPage extends React.Component {
formatEmailValues() { return 'formatEmailValues return value'; }
async onSubmit(values, applicaitonId) {
try {
this.setState({ loading: true });
const response = await sendEmail(this.formatEmailValues(values), applicaitonId);
console.log(response)
this.setState({ loading: false });
if (response.status !== 'error') {
this.props.history.push('/dashboard');
} else {
alert(
`Something was wrong with your email. Error: ${response.message}`
);
}
} catch (error) {
console.error('Error while sending email!');
console.error(error);
this.setState({ loading: false });
}
}
render() { return null; }
}
describe('EmailPage', () => {
test('onSubmit', async () => {
const historyMock = { push: jest.fn() };
const wrapper = shallow(<EmailPage history={historyMock} />);
const instance = wrapper.instance();
let sendEmailResolve;
sendEmail = jest.fn(() => new Promise(resolve => { sendEmailResolve = resolve; }));
const formatEmailValuesSpy = jest.spyOn(EmailPage.prototype, 'formatEmailValues');
const promise = instance.onSubmit(['value1', 'value2'], 'applicationId');
expect(wrapper.state().loading).toBe(true); // Success!
expect(formatEmailValuesSpy).toHaveBeenCalledWith(['value1', 'value2']); // Success!
expect(sendEmail).toHaveBeenCalledWith('formatEmailValues return value', 'applicationId'); // Success!
sendEmailResolve({ status: 'success' }); // simulate sendEmail resolving
await promise; // let onSubmit finish
expect(wrapper.state().loading).toBe(false); // Success!
expect(historyMock.push).toHaveBeenCalledWith('/dashboard'); // Success!
})
})
Я оставлю читателю в качестве упражнения упражнение по реализации случая error
.
(... но для быстрого запускаэти усилия, вы захотите издеваться global.alert
и позвонить sendEmailResolve({ status: 'error' });
во время теста)