我正在尝试在抛出错误的情况下使用 jest 和 react 测试库对自定义钩子进行单元测试,但我无法捕捉到实际的错误消息,这是我目前的代码:
我的第一个钩子:
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;
test.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()
});
});
我的逻辑是首先创建一个钩子,对其进行单元测试,然后创建组件,在那里添加钩子并使用钩子集成测试该组件。我错过了什么,或者我的方法完全错误?
答案 0 :(得分:1)
一个好的方法是测试已经包含钩子的组件本身。
如果您认为需要在没有组件的情况下测试钩子,您可以使用 @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'));
}
});
});