[deprecated?react-hooks-testing-library
将返回被测试钩子抛出的任何错误。
可能是我的误解,但看起来现在主要@testing-library/react
的实现失去了这个功能?
我是这么想的:
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();
});
…也许是这样的实现?
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:如果有人感兴趣的话,我实际上做了一个类型安全的版本-但是类型注释使示例在SO上更难阅读。
如果您正在使用Jest,您可以这样做:
import { renderHook } from '@testing-library/react'
function useFail() {
throw new Error('Oops')
}
it('should throw', () => {
expect(() => {
renderHook(() => useFail())
}).toThrow(Error('Oops'))
})