React 的新手,但不是测试应用程序的新手。
我想确保每次组件抛出错误时都会显示 ErrorBoundary 消息。如果你不知道我所说的 ErrorBoundary 是什么意思,这里是一个 link .
假设我们需要测试 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/