首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >抛出错误的测试钩子

抛出错误的测试钩子
EN

Stack Overflow用户
提问于 2022-06-12 21:02:53
回答 1查看 892关注 0票数 0

不推荐的?react-hooks-testing-library将返回由测试钩子引发的任何错误。

可能是我的误解,但看起来现在主要的@testing-library/react中的实现已经失去了这个特性?

我是这么想的:

代码语言:javascript
复制
import { safeRenderHook } from './safeRenderHook';

function useFail() {
  throw 'fail';
}

function useSucceed() {
  return 'success';
}

it('should fail', () => {
  const { result, error } = safeRenderHook(() => useFail());
  expect(error.current).toEqual('fail');
  expect(result.current).toBeUndefined();
});

it('should succeed', () => {
  const { result, error } = safeRenderHook(() => useSucceed());
  expect(result.current).toEqual('success');
  expect(error.current).toBeUndefined();
});

..。也许像这样的实现?

代码语言:javascript
复制
import { render } from '@testing-library/react';
import React from 'react';

/**
 * A variant of `renderHook()` which returns `{ result, error }` with `error`
 * being set to any errors thrown by the hook. Otherwise, it behaves the same as
 * `renderHook()`.
 *
 * ```
 * const useFail = () => Promise.reject('fail!');
 *
 * it('should fail') {
 *  const { error } = safeRenderHook(() => useFail());
 *  expect(error).toEqual('fail!');
 * }
 * ```
 *
 * >Note: since this effectively swallows errors, you should be sure to
 * explicitly check the returned `error` value.
 */
export function safeRenderHook(renderCallback, options = {}) {
  const { initialProps = [], wrapper } = options;
  const result = React.createRef();
  const error = React.createRef();

  function TestComponent({ hookProps }) {
    let pendingError;
    let pendingResult;

    try {
      pendingResult = renderCallback(...hookProps);
    } catch (err) {
      pendingError = err;
    }

    React.useEffect(() => {
      result.current = pendingResult;
      error.current = pendingError;
    });

    return null;
  }

  const { rerender: baseRerender, unmount } = render(<TestComponent hookProps={initialProps} />, { wrapper });

  function rerender(rerenderCallbackProps) {
    return baseRerender(<TestComponent hookProps={rerenderCallbackProps} />);
  }

  return { result, error, rerender, unmount };
}

ps:如果有人感兴趣的话,我实际上做了一个类型安全的版本,但是类型注释使得这个例子更难理解。

EN

回答 1

Stack Overflow用户

发布于 2022-08-15 15:29:31

如果您正在使用Jest,您可以这样做:

代码语言:javascript
复制
import { renderHook } from '@testing-library/react'

function useFail() {
  throw new Error('Oops')
}

it('should throw', () => {
  expect(() => {
    renderHook(() => useFail())
  }).toThrow(Error('Oops'))
})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72595857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档