如何测试ErrorBoundary的后备组件?

布兰登·达勒姆(Brandon Durham)

我有这个组成部分:

import React, { lazy, Suspense } from 'react';
import { ErrorBoundary } from '../ErrorBoundary';

const FALLBACK = <svg aria-label="" data-testid="icon-fallback" viewBox="0 0 21 21" />;

const ERROR = (
    <svg data-testid="icon-notdef" viewBox="0 0 21 21">
        <path d="M0.5,0.5v20h20v-20H0.5z M9.1,10.5l-6.6,6.6V3.9L9.1,10.5z M3.9,2.5h13.2l-6.6,6.6L3.9,2.5z M10.5,11.9l6.6,6.6H3.9 L10.5,11.9z M11.9,10.5l6.6-6.6v13.2L11.9,10.5z" />
    </svg>
);

export const Icon = ({ ariaLabel, ariaHidden, name, size }) => {
    const LazyIcon = lazy(() => import(`../../assets/icons/${size}/${name}.svg`));
    return (
        <i aria-hidden={ ariaHidden }>
            <ErrorBoundary fallback={ ERROR }>
                <Suspense fallback={ FALLBACK }>
                    <LazyIcon aria-label={ ariaLabel } data-testid="icon-module" />
                </Suspense>
            </ErrorBoundary>
        </i>
    );
};

我正在尝试测试不存在通过SVG的条件,从而呈现<ErrorBoundary />回退。ErrorBoundary在浏览器中有效,但在我的测试中无效。

这是失败的测试:

test('shows notdef icon', async () => {
    const { getByTestId } = render(<Icon name='doesnt-exist' />);
    const iconModule = await waitFor(() => getByTestId('icon-notdef'));
    expect(iconModule).toBeInTheDocument();
});

我收到此错误消息:

TestingLibraryElementError:无法通过以下方式找到元素:[data-testid =“ icon-notdef”]“。

如何在测试中访问ErrorBoundary后备用户界面?

编辑

这是<ErrorBoundary />组件的代码

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export class ErrorBoundary extends Component {
    constructor(props) {
        super(props);
        this.state = {
            error: '',
            errorInfo: '',
            hasError: false,
        };
    }

    static getDerivedStateFromError(error) {
        return { hasError: true, error };
    }

    componentDidCatch(error, errorInfo) {
        console.error({ error, errorInfo });
        this.setState({ error, errorInfo });
    }

    render() {
        const { children, fallback } = this.props;
        const { error, errorInfo, hasError } = this.state;

        // If there is an error AND a fallback UI is passed in…
        if (hasError && fallback) {
            return fallback;
        }

        // Otherwise if there is an error with no fallback UI…
        if (hasError) {
            return (
                <details className="error-details">
                    <summary>There was an error.</summary>
                    <p style={ { margin: '12px 0 0' } }>{error && error.message}</p>
                    <pre>
                        <code>
                            {errorInfo && errorInfo.componentStack.toString()}
                        </code>
                    </pre>
                </details>
            );
        }

        // Finally, render the children.
        return children;
    }
}

ErrorBoundary.propTypes = {
    children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
    fallback: PropTypes.node,
};

…这是我为测试得到的DOM的完整错误:

shows notdef icon

    TestingLibraryElementError: Unable to find an element by: [data-testid="icon-notdef"]

    <body>
      <div>
        <i
          aria-hidden="false"
          class="Icon Icon--sm"
        >
          <span
            aria-label=""
            data-testid="icon-module"
          />
        </i>
      </div>
    </body>

    <html>
      <head />
      <body>
        <div>
          <i
            aria-hidden="false"
            class="Icon Icon--sm"
          >
            <span
              aria-label=""
              data-testid="icon-module"
            />
          </i>
        </div>
      </body>
    </html>Error: Unable to find an element by: [data-testid="icon-notdef"]

最后,我的SVG模拟:

import React from 'react';

const SvgrMock = React.forwardRef(
    function mySVG(props, ref) {
        return <span { ...props } ref={ ref } />;
    },
);

export const ReactComponent = SvgrMock;
export default SvgrMock;
死了

正如评论中所讨论的,该模拟很可能避免了该错误。尝试使用抛出错误的新模拟重新模拟SVG文件。

// tests that require unmocking svg files
describe('non existent svg', () => {
  beforeAll(() => {
    jest.mock('.svg', () => {
      throw new Error('file not found')
    });
  });
  
  test('shows notdef icon', async () => {
    const { getByTestId } = render(<Icon name='doesnt-exist' />);
    const iconModule = await waitFor(() => getByTestId('icon-notdef'));
    expect(iconModule).toBeInTheDocument();
  });

  afterAll(() => jest.unmock('.svg'))
})

必须包装它,以确保仅在测试(beforeAll- afterAll期间重新模拟SVG文件,以免干扰其余测试。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何在Typescript中正确键入React ErrorBoundary类组件?

来自分类Dev

如何使用Modernizr对HTML5后备进行测试

来自分类Dev

如何从后备bean中查找包括复合组件ID的组件ID

来自分类Dev

如何测试反应连接的组件以及如何测试组件?

来自分类Dev

测试 Angular 1.5 组件:如何测试 $onChanges

来自分类Dev

Redux:如何测试连接的组件?

来自分类Dev

如何将后备样式属性应用于React JS组件?

来自分类Dev

如何在Chrome中禁用HTML5功能以测试后备?

来自分类Dev

如何测试组件行为以响应诺言

来自分类Dev

测试时如何从组件获取属性?

来自分类Dev

如何使用useReducer挂钩测试组件?

来自分类Dev

测试功能如何从外部导入组件中?

来自分类Dev

如何在React中测试类组件

来自分类Dev

如何使用Jest测试JSX Vue组件

来自分类Dev

如何使用内部的<Router>标签测试组件?

来自分类Dev

如何在类组件中测试方法?

来自分类Dev

如何测试硬件组件以找出哪个是坏的?

来自分类Dev

如何测试基于jQuery-UI的组件?

来自分类Dev

反应如何测试与setTimeout反应组件

来自分类Dev

如何测试组件行为以响应诺言

来自分类Dev

如何测试未在 React 中导出的组件

来自分类Dev

如何测试传递给组件的方法

来自分类Dev

我应该如何测试这个角度组件?

来自分类Dev

如何使用多个子组件测试React组件?

来自分类Dev

如何测试使用 props 渲染其他组件的 React 组件?

来自分类Dev

Angular 9单元测试:如何模拟测试组件的导入?

来自分类Dev

如何使用反应测试库测试反应组件的props值

来自分类Dev

如何使用React测试库测试组件的内部功能

来自分类Dev

反应测试。如何测试反应组件内部的功能

Related 相关文章

热门标签

归档