I’m using RTL and have a test:
describe('Image component', () => {
it('renders avatar', () => {
render(<Image {...args} />);
const element = document.querySelector('img');
expect(element.src).toContain(args.image);
});
});
After switching on strictNullChecks
, I got error on final line saying 'element' is possibly 'null'
. Yes, I can make a null check before expect
line, but doesn’t it render pointless test then? Because if element
won’t be found, I want test to fail.
2
Answers
I think this should be handled by using Ts type assertion.
Like:
OR
Another approach is to check for element truthiness else fail the test
Check related Question
You should avoid using
querySelector
as much as possible (advised by the creator of React Testing Library himself https://kentcdodds.com/blog/common-mistakes-with-react-testing-library#using-container-to-query-for-elements).If you want to test your image has the correct
src
attribute :