skip to Main Content

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


  1. I think this should be handled by using Ts type assertion.

    Like:

    const element = document.querySelector('img') as HTMLImageElement;
    

    OR

    const element = <HTMLImageElement>document.querySelector('img');
    

    Another approach is to check for element truthiness else fail the test

    if (element) {
          expect(element.src).toContain(args.image);
        } else {
          fail('Image element not found');
        }
    

    Check related Question

    Login or Signup to reply.
  2. 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 :

    import { render, screen } from '@testing-library/react';
    
    ...
    
    describe('Image component', () => {
      it('renders avatar', () => {
        render(<Image {...args} />);
        const element = screen.getByRole('img');
        expect(element).toHaveAttribute('src', args.image);
      });
    });
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search