简体   繁体   English

Jest/Enzyme 测试 React 组件在 try/catch 中使用 async/await 方法

[英]Jest/Enzyme test React component with async/await method in try/catch

I've been struggling trying to test this method with Jest for ages, searching online doesn't seem to help.多年来,我一直在努力尝试用 Jest 测试这种方法,在线搜索似乎无济于事。 I'm thinking I need to refactor this method but I'm not sure how to do it in such a way that is testable.我想我需要重构这个方法,但我不确定如何以这种可测试的方式来做。

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

Any ideas?有任何想法吗?

This should get you started:这应该让你开始:

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!
  })
})

I'll leave it as an exercise to the reader to implement the error case.我将把它作为练习留给读者来实现error案例。

(...but to jumpstart that effort, you will want to mock global.alert and call sendEmailResolve({ status: 'error' }); during the test) (...但要快速启动这项工作,您需要在测试期间模拟global.alert并调用sendEmailResolve({ status: 'error' });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM