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:
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
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 ?