我正在尝试使用 jest 和 React 测试库对自定义钩子(Hook)进行单元测试,在抛出错误的情况下,但我无法捕获实际的错误消息,这是迄今为止我的代码:
我的第一个钩子(Hook):
import react from 'react';
const useFirstHook = () => {
//I will add conditional logic later
throw new Error('my custom error is thrown')
const test1 = 'I am test 1';
return {
test1
};
};
export default useFirstHook;
测试.js
import React from 'react';
import { render } from '@testing-library/react';
import useFirstHook from './useFirstHook';
describe('useFirstHook', () => {
//I also tried adding jest.spy but no luck
/* beforeAll(() => {
jest.spyOn(console, 'error').mockImplementation(() => {})
}); */
it('test 1', () => {
let result;
const TestComponent = () => {
result = useFirstHook()
return null;
};
render(<TestComponent />)
//expect()
});
});
我的逻辑是首先创建一个钩子(Hook),对其进行单元测试,然后创建组件,在其中添加钩子(Hook)并使用钩子(Hook)集成测试该组件。我错过了什么,或者我的方法完全错误?
最佳答案
一个好的方法是测试已经包含钩子(Hook)的组件本身。
如果您认为需要在没有组件的情况下测试钩子(Hook),您可以使用@testing-library/react-hooks
包,例如:
const useFirstHook = (shouldThrow = false) => {
// throw onmount
useEffect(() => {
if (shouldThrow) throw new Error('my custom error is thrown');
}, [shouldThrow]);
return {
test1: 'I am test 1'
};
};
describe('useFirstHook', () => {
it('should not throw', () => {
const { result } = renderHook(() => useFirstHook(false));
expect(result.current.test1).toEqual('I am test 1');
});
it('should throw', () => {
try {
const { result } = renderHook(() => useFirstHook(true));
expect(result.current).toBe(undefined);
} catch (err) {
expect(err).toEqual(Error('my custom error is thrown'));
}
});
});
关于reactjs - 使用 Jest 和 react 测试库进行单元测试自定义 Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66545990/