首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何测试React ErrorBoundary

如何测试React ErrorBoundary
EN

Stack Overflow用户
提问于 2018-03-11 21:41:25
回答 2查看 7.5K关注 0票数 9

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

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

我使用Mocha + Chai + Enzyme

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

测试配置

代码语言:javascript
复制
// 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-一些后来的想法

在阅读了this conversation关于连接组件的最佳测试方法(涉及类似问题)之后,我知道我不必担心componentDidCatch会捕捉到错误。React经过了充分的测试,这确保了无论何时抛出错误,它都会被捕获。

因此,只有两个测试:

1:确保ErrorBoundary在出现错误时显示消息

代码语言:javascript
复制
// 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.');
    });
});

2:确保组件包装在ErrorBoundary中(在React counter example中是<App />,这是误导性的。我们的想法是在最接近的父组件上这样做)。

注意: 1)它需要在父组件上完成,2)我假设子组件是简单的组件,而不是容器,因为它可能需要更多的配置。进一步的思考:这个测试可以用parent而不是descendents写得更好……

代码语言:javascript
复制
// error_boundary_test.js
import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';

import App from './some/path/app';

describe('App', ()=>{
    it('wraps children in ErrorBoundary', ()=>{
        const component = mount(<App />);
        expect(component).to.have.descendants(ErrorBoundary);
    });
EN

回答 2

Stack Overflow用户

发布于 2020-04-21 23:06:38

使用React Testing Library测试ErrorBoundary组件

代码语言:javascript
复制
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

代码语言:javascript
复制
import { render } from '@testing-library/react'

const renderProviders = (ui: React.ReactElement) => render(ui, {})
票数 9
EN

Stack Overflow用户

发布于 2018-08-29 21:59:25

这是我在没有设置组件状态的情况下进行的尝试:

ErrorBoundary:

代码语言:javascript
复制
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>;

测试:

代码语言:javascript
复制
it('Renders ErroredContentPresentation Fallback if error ', ()=>{
  const wrappedComponent = props => {
    throw new Error('Errored!');
  };
  const component = withErrorBoundary( wrappedComponent )(props);
  expect(mount(component).html()).toEqual(shallow(<ErroredContentPresentation/>).html());
});
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49220626

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档