使用React测试库 /开玩笑测试错误边界:

发布于 2025-02-05 20:46:05 字数 2336 浏览 4 评论 0原文

我正在尝试为错误边界hoc编写测试。但是,当我模拟包装组件中的抛出错误时,我的测试会失败,因为我丢了相同的错误,就像它似乎没有意识到此错误是用于测试的。我不确定我在这里做错了什么。

这是errorboundary hoc:


interface StateProps {
  error: unknown;
  info: unknown;
}

interface ErrorBoundaryProps {
  createNotification(...args: any): void;
}

const connector = connect(null, {
  createNotification: createNotificationAction,
});

export const withErrorBoundary = <P extends object>(TargetComponent: React.ComponentType<P>) => {
  class ErrorBoundary extends React.Component<ErrorBoundaryProps, StateProps> {
    constructor(props: ErrorBoundaryProps) {
      super(props);
      this.state = {
        error: null,
        info: null,
      };
    }

    public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
      this.props.createNotification({
        alertType: 'error',
        message: `${TargetComponent.name} is not being rendered. Error: ${error.message}`,
      });
      this.setState({ error, info: errorInfo });
    }

    public render() {
   
      const { ...props } = this.props;
      if (this.state.error instanceof Error) {
        return null;
      }
      return <TargetComponent {...(props as P)} />;
    }
  }

  return connector(ErrorBoundary) as any;
};

这是测试:


describe('ErrorBoundary HOC', () => {
  let store;
  let createNotification;
  let props;

  beforeEach(() => {
    store = configureStore(defaultState);
    createNotification = jest.fn();

    props = {
      createNotification,
    };

  });

  test('Renders nothing if error', async () => {
    const targetComponent = () => {
      throw new Error('Errored!');
    };
    const WrappedComponent = withErrorBoundary(targetComponent);
    const RenderedComponent = render(
      <BrowserRouter>
        <Provider store={store}>
          <WrappedComponent {...props} />
        </Provider>
      </BrowserRouter>
    );

    await waitFor(() => expect(() => WrappedComponent.toThrow()));
    expect(RenderedComponent.container.hasChildNodes()).toBeFalsy();
    await waitFor(() => expect(createNotification).toHaveBeenCalled());

 
  });

});

到目前为止,我已经发现错误是在测试中呈现之前投掷的。但不确定如何解决这个问题。

感谢您提前的帮助。

I am trying to write test for my error boundary hoc. But when I mock throwing error in my wrapped component my test gets fail because of the same error I throw, like it seems like it doesnt recognize that this error was intended for testing. I am not sure what I am doing wrong here.

This is ErrorBoundary HOC:


interface StateProps {
  error: unknown;
  info: unknown;
}

interface ErrorBoundaryProps {
  createNotification(...args: any): void;
}

const connector = connect(null, {
  createNotification: createNotificationAction,
});

export const withErrorBoundary = <P extends object>(TargetComponent: React.ComponentType<P>) => {
  class ErrorBoundary extends React.Component<ErrorBoundaryProps, StateProps> {
    constructor(props: ErrorBoundaryProps) {
      super(props);
      this.state = {
        error: null,
        info: null,
      };
    }

    public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
      this.props.createNotification({
        alertType: 'error',
        message: `${TargetComponent.name} is not being rendered. Error: ${error.message}`,
      });
      this.setState({ error, info: errorInfo });
    }

    public render() {
   
      const { ...props } = this.props;
      if (this.state.error instanceof Error) {
        return null;
      }
      return <TargetComponent {...(props as P)} />;
    }
  }

  return connector(ErrorBoundary) as any;
};

and here is the test:


describe('ErrorBoundary HOC', () => {
  let store;
  let createNotification;
  let props;

  beforeEach(() => {
    store = configureStore(defaultState);
    createNotification = jest.fn();

    props = {
      createNotification,
    };

  });

  test('Renders nothing if error', async () => {
    const targetComponent = () => {
      throw new Error('Errored!');
    };
    const WrappedComponent = withErrorBoundary(targetComponent);
    const RenderedComponent = render(
      <BrowserRouter>
        <Provider store={store}>
          <WrappedComponent {...props} />
        </Provider>
      </BrowserRouter>
    );

    await waitFor(() => expect(() => WrappedComponent.toThrow()));
    expect(RenderedComponent.container.hasChildNodes()).toBeFalsy();
    await waitFor(() => expect(createNotification).toHaveBeenCalled());

 
  });

});

What I have been found so far is the error is throwing before render in the test. but not sure how to solve this.

Thanks for your help in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

紧拥背影 2025-02-12 20:46:08

在函数组件中,除了useefffect()中的内容外,在返回之前执行返回之前的所有内容。

在这种情况下,targetComponent没有返回或JSX渲染,但仍然适用。

您可以在这样的渲染之后丢弃错误,

const targetComponent = () => {
  useEffect(() => {
    throw new Error('Errored!');
  }, [])
}

我不确定是否足以为您提供所需的测试,但这是一个细致点。

In a functional component, everything before the return is executed before rendering, except for stuff in useEfffect().

In this case targetComponent has no return or JSX to render, but it still applies.

You can throw the error after render like this

const targetComponent = () => {
  useEffect(() => {
    throw new Error('Errored!');
  }, [])
}

I'm not sure if it's enough to give you the desired test, but it's a strating point.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文