Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object contains a link in React Testing Library

Having the following unit test:

  const MY_URL = 'example.com'
  it('should render MyComponent with url', () => {
    const { getByTestId } = render(<MyComponent />);
    const myLink = getByTestId(TestIds.LINK);
    expect(loggingLink).toContain(MY_URL);
  });

The test fails with the following message:

 Expected value:  "example.com"
 Received object: <div class="m-3" data-testid="test-link"><a href="example.com">my-link</a></div>

So it seems that toContain doesn't check what is inside of that object. Is there a method to check that the URL is inside the object?

like image 513
Leo Messi Avatar asked Dec 18 '25 15:12

Leo Messi


1 Answers

You can get the anchor element with ByRole query. Just search it with link and then check the attribute href:

// I used screen in this case, but you can get getByRole from render.
const anchorElement = screen.getByRole('link');

expect(anchorElement).toBeInTheDocument();

expect(anchorElement).toHaveAttribute('href', 'example.com');

Anchor elements have link role only when href attribute is present, otherwise no corresponding role. You can check more about it here.

like image 56
Luis Paulo Pinto Avatar answered Dec 20 '25 05:12

Luis Paulo Pinto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!