[英]unit test custom hook with jest and react testing library
I am trying to unit test a custom hook using jest and react testing library in scenario where error is thrown but I am not able to catch the actual error message, here is my code so far:我正在尝试使用 jest 对自定义钩子进行单元测试,并在引发错误但我无法捕获实际错误消息的情况下反应测试库,这是我的代码到目前为止:
my first 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;
test.js测试.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()
});
});
my logic is to first create a hook, unit test it and then create component, add hook there and test that component with hook integration as well.我的逻辑是首先创建一个钩子,对其进行单元测试,然后创建组件,在那里添加钩子并使用钩子集成测试该组件。 what am I missing, or my approach is completely wrong?
我错过了什么,或者我的方法完全错误?
A good approach would be testing the component itself, that already contains the hook.一个好的方法是测试已经包含钩子的组件本身。
In case you consider that the hook needs to be test without the component, you can use @testing-library/react-hooks
package, something like:如果您认为钩子需要在没有组件的情况下进行测试,您可以使用
@testing-library/react-hooks
package,例如:
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'));
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.