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

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


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 to check the href attribute of your <a>:

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


I found a solution that may help others. The <a> element is considered a link role by React Testing Library. This should work:

expect(screen.getByRole('link')).toHaveAttribute('href', 'https://www.test.com');


You can simply use this instead:

expect(getByText("Click Me").href).toBe("https://www.test.com/")