Raygun在开玩笑地进行单元测试时似乎有问题:ReferenceError: rg4js is not defined
。
我正在实现react文档中定义的错误边界。该组件是一个包装器,当抛出错误时,它将呈现已定义的错误组件。
import React from 'react';
import { RouteComponentProps, withRouter } from 'react-router-dom';
import { RaygunV2 } from 'raygun4js';
import { ROUTES } from 'src/core/constants';
import { DisplayError } from '../displayError/displayError';
declare let rg4js: RaygunV2;
export type Props = RouteComponentProps;
interface State {
hasError: boolean;
}
export class ErrorBoundary extends React.Component<Props, State> {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return {
hasError: true,
};
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
const { message } = error;
const { componentStack: stack } = errorInfo;
rg4js('send', { message, stack });
}
render() {
if (this.state.hasError) {
return <DisplayError />;
}
return this.props.children;
}
}
export default withRouter(ErrorBoundary);
为了进行测试,我创建了一个假部件作为孩子,该孩子是否抛出错误。当不抛出错误时,它可以很好地呈现。抛出错误时,由于调用了raygun函数,因此单元测试无法正常工作,因为它无法识别raygun函数。
import React from 'react';
import { mount } from 'enzyme';
import { createMemoryHistory, createLocation } from 'history';
import { MemoryRouter } from 'react-router-dom';
import ErrorBoundary, { Props } from '../errorBoundary';
jest.mock('../../displayError/displayError', () => ({
DisplayError: 'mock-display-error',
}));
class FakeComponent extends React.Component<{ error: boolean }> {
componentDidMount() {
const { error } = this.props;
if (error) throw new Error('Big error');
}
render() {
return <div>child</div>;
}
}
describe('<ErrorBoundary />', () => {
it('renders', () => {
const mockProps: Props = {
match: {
params: '',
isExact: true,
path: '/',
url: '/',
},
history: createMemoryHistory(),
location: createLocation('/'),
};
const component = mount(
<MemoryRouter>
<ErrorBoundary {...mockProps}>
<FakeComponent error={false} />
</ErrorBoundary>
</MemoryRouter>
);
expect(component.render()).toMatchSnapshot();
});
it('renders with error', () => {
const mockProps: Props = {
match: {
params: '',
isExact: true,
path: '/',
url: '/',
},
history: createMemoryHistory(),
location: createLocation('/'),
};
const component = mount(
<MemoryRouter>
<ErrorBoundary {...mockProps}>
<FakeComponent error={true} />
</ErrorBoundary>
</MemoryRouter>
);
expect(component.render()).toMatchSnapshot();
});
});
关于如何使其工作的任何想法?