Search code examples
reactjsjestjsanchorhrefreact-testing-library

How to test anchor's href with react-testing-library


I am trying to test my anchor tag. Once I click it, I want to see if the window.location.href is what I expect.

I've tried to render the anchor, click it, and then test window.location.href:

test('should navigate to ... when link is clicked', () => {
  const { getByText } = render(<a href="https://test.com">Click Me</a>);

  const link = getByText('Click Me');

  fireEvent.click(link);

  expect(window.location.href).toBe("https://www.test.com/");
});

I am expecting the test to pass, but instead the window.location.href is just "http://localhost/" meaning it is not getting updated for whatever reason. I even tried wrapping my expect with await wait, but that didn't work either. I can't find much information about testing anchors with react-testing-library. Maybe there is even a better way to test them than what I am doing. 🤷‍♂️


Solution

  • Jest uses jsdom to run its test. jsdom is simulating a browser, but it has some limitations. One of these limitations is the fact that you can't change the location. If you want to test that your link works, I suggest using getByRole with a name argument to check the href attribute of your <a>:

    expect(screen.getByRole('link', { name: 'Click Me' })).toHaveAttribute('href', 'https://www.test.com/')
    

    Historical Note

    Previously this answer recommended the following, but because it relies on closest (whose use is discouraged by React Testing Library's emphasis on user-visible testing) it is considered a worse solution:

    expect(screen.getByText('Click Me').closest('a')).toHaveAttribute('href', 'https://www.test.com/')