如何测试React ErrorBoundary

时间:2018-03-11 13:41:25

标签: reactjs unit-testing testing enzyme

React的新功能,但不是测试应用程序。

我想确保每次组件抛出错误时都会显示ErrorBoundary消息。如果你不知道ErrorBoundary我的意思,这里是link

我使用Mocha + Chai + Enzyme

我们需要使用以下测试配置测试React counter example

测试配置

HTTP Error 500 This page is not loading

更新1 - 后来的一些想法

在阅读this conversation关于连接组件的最佳测试方法(涉及类似问题)之后,我知道我不必担心// DOM import jsdom from 'jsdom'; const {JSDOM} = jsdom; const {document} = (new JSDOM('<!doctype html><html><body></body></html>')).window; global.document = document; global.window = document.defaultView; global.navigator = global.window.navigator; // Enzyme import { configure } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; configure({ adapter: new Adapter() }); // Chai import chai from 'chai'; import chaiEnzyme from 'chai-enzyme'; chai.use(chaiEnzyme()); 捕获错误。反应经过充分测试,确保无论何时抛出错误都会被捕获。

因此,只有测试两个测试:

1:如果出现任何错误,请确保ErrorBoundary显示消息

componentDidCatch

2:确保组件被包装在ErrorBoundary中(React counter example// error_boundary_test.js import React from 'react'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import ErrorBoundary from './some/path/error_boundary'; describe('Error Boundary', ()=>{ it('generates a error message when an error is caught', ()=>{ const component = shallow(<ErrorBoundary />); component.setState({ error: 'error name', errorInfo: 'error info' }); expect(component).to.contain.text('Something went wrong.'); }); }); ,这是误导。想法是在最近的父组件上执行此操作。)

注意:1)需要在父组件上完成,2)我假设子组件是简单组件,而不是容器,因为它可能需要更多配置。 进一步的想法:使用<App />代替parent ...

可以更好地编写此测试
descendents

2 个答案:

答案 0 :(得分:3)

这是我未设置组件状态的尝试:

ErrorBoundary:

_GLOBAL__sub_I_main:

测试:

import React, { Component } from 'react';
import ErroredContentPresentation from './ErroredContentPresentation';

class ContentPresentationErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    this.setState({ hasError: true });
  }

  render() {
    return this.state.hasError ? <ErroredContentPresentation /> : this.props.children;
  }
}

export const withErrorBoundary = WrappedComponent =>
  props => <ContentPresentationErrorBoundary>
            <WrappedComponent {...props}/>
          </ContentPresentationErrorBoundary>;

答案 1 :(得分:0)

使用React Testing库测试ErrorBoundary组件

const Child = () => {
  throw new Error()
}

describe('Error Boundary', () => {
  it(`should render error boundary component when there is an error`, () => {
    const { getByText } = renderProviders(
      <ErrorBoundary>
        <Child />
      </ErrorBoundary>
    )
    const errorMessage = getByText('something went wrong')
    expect(errorMessage).toBeDefined()
  })
})

renderProviders

import { render } from '@testing-library/react'

const renderProviders = (ui: React.ReactElement) => render(ui, {})