开玩笑/酶在try / catch中使用async / await方法测试React组件

时间:2019-03-21 18:20:23

标签: javascript reactjs ecmascript-6 jestjs enzyme

多年以来,我一直在努力尝试用Jest测试这种方法,在线搜索似乎无济于事。我想我需要重构这种方法,但是我不确定如何以可测试的方式来实现它。

class EmailPage extends Component {
  ...
  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 });
    }
  }
  ...
}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这应该使您入门:

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' });