reactjs - 如何测试 React ErrorBoundary

标签 reactjs unit-testing testing enzyme

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

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

我正在使用 Mocha + Chai + Enzyme .

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

测试配置

// 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在出现任何错误时显示消息

// 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 ...

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

最佳答案

使用 React 测试库测试 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()
  })
})

渲染器

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

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

关于reactjs - 如何测试 React ErrorBoundary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49220626/

相关文章:

angular - 如何在Angular中为带有星号*前缀的结构指令编写单元测试

python - 如何使用 python 在机器人框架中导入和使用用户定义的类

testing - Sinatra、Rack::Test 和条件 GET 请求

unit-testing - 如何使用 pub run test 运行特定的 Dart _test 文件?

javascript - 在 React JavaScript 中显示/映射嵌套 JSON 字段

javascript - 覆盖现有的react.js类

javascript - 验证Token JWT是否有效

javascript - Context Api 状态没有改变

c# - 单元测试 : How to check if generated javascript (string) is valid javascript

flutter - 将生成的模拟类注入(inject)测试“环境”