diff --git a/test/@helpers/jest-setup.ts b/test/@helpers/jest-setup.ts index 79318d0..2ef55f0 100644 --- a/test/@helpers/jest-setup.ts +++ b/test/@helpers/jest-setup.ts @@ -5,3 +5,6 @@ import React from 'react' // Define global React to solve "ReferenceError: React is not defined in jest tests" // https://stackoverflow.com/questions/58980934/referenceerror-react-is-not-defined-in-jest-tests global.React = React + +// 不打印 console 错误信息 +jest.spyOn(console, 'error').mockImplementation(jest.fn()) diff --git a/test/core-react/components/ErrorBoundary.test.tsx b/test/core-react/components/ErrorBoundary.test.tsx new file mode 100644 index 0000000..0ea5397 --- /dev/null +++ b/test/core-react/components/ErrorBoundary.test.tsx @@ -0,0 +1,41 @@ +import ErrorBoundary from '@core-react/components/ErrorBoundary' +import { render, screen } from '@testing-library/react' + +const ERROR_TEXT = '_ERROR_FROM_COMPONENT_' + +const ErrorComponent = () => { + throw new Error(ERROR_TEXT) +} + +describe('ErrorBoundary 验证', () => { + test('组件抛出错误应该被捕获并展示出来', async () => { + render( + + + + ) + const node = screen.queryByText(new RegExp(ERROR_TEXT)) + expect(node).toBeInTheDocument() + }) + + test('设置为 silent 模式时,组件错误不应该展示出来', async () => { + render( + + + + ) + const node = screen.queryByText(new RegExp(ERROR_TEXT)) + expect(node).not.toBeInTheDocument() + }) + + test('自定义错误时,应该捕获错误并展示自定义的错误信息', async () => { + const CUSTOM_ERROR_TEXT = 'CUSTOM_ERROR_TIPS' + render( + CUSTOM_ERROR_TEXT}> + + + ) + const node = screen.queryByText(new RegExp(CUSTOM_ERROR_TEXT)) + expect(node).toBeInTheDocument() + }) +})