0

我正在尝试测试错误边界组件,如果有任何错误,错误边界组件将捕获它并显示正确的消息。

我还添加了上面的错误边界组件代码以供参考,我还尝试在编写测试用例时模拟 componentDidCatch 方法,但它对我也不起作用。

const Something = () => null;

describe('ErrorBoundary', () => {
  it('should display an ErrorMessage if wrapped component throws', () => {
    const wrapper = mount(
      <ErrorBoundary>
        <Something />
      </ErrorBoundary>
    );

    const error = new Error('test');

    wrapper.find(Something).simulateError(error);

    /* The rest fo your test */
  }
}

上面的代码是Errorboundary.test.js usingErrorsimulator

    import './ErrorBoundary.scss';

import { PropTypes } from 'prop-types';
import React from 'react';
class ErrorBoundary extends React.Component {
  state = {
    errorMessage: '',
  };

  static getDerivedStateFromError(error) {
    return { errorMessage: error.toString() };
  }

  componentDidCatch(error, info) {
    this.logErrorToServices(error.toString(), info.componentStack);
  }

  // A fake logging service.
  logErrorToServices = console.log;

  render() {
    if (this.state.errorMessage) {
      return (
        <div className="test">
          Something went wrong, please try again or contact customer support at
          xxxx
        </div>
      );
    }
    return this.props.children;
  }
}
ErrorBoundary.propTypes = {
  children: PropTypes.func,
};

export default ErrorBoundary;
4

0 回答 0