SAKURA
SAKURA

Reputation: 986

React-testing library: test router redirect

How do I test that the router link changed after a redirect?

After clicking on a button, it should redirect to another page with url ending in "new_page".

This is what I tried, but I keep getting undefined.

  {getByTestId} = render(<MyButton />);      

  const mockBoxIconButton = getByTestId('box-icon-button');

  mockBoxIconButton.click();

  console.log(getByTestId('box-icon-button').closest('a')); # undefined
  console.log(getByTestId('box-icon-button').location.href);  # undefined

  expect(
    mockExtractionButton.getByTestId('box-icon-button').closest('a')
  ).toHaveAttribute('href', /http[a-zA-Z0-9:\/-]*new_page/);
});

Upvotes: 0

Views: 5096

Answers (1)

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

The aim of react-testing-library is not to test code implementation but rather testing how a user would perceive UI interactions. So in your case, I would suggest to not look for /new_page path after routing. Instead test what the user would interact with after redirecting to the page. It could be another button interaction or readable data inside heading, paragraph or span tags (whatever your most important interaction feels like).

Please refer the following article for more clarity on this:-

https://kentcdodds.com/blog/introducing-the-react-testing-library

Upvotes: 2

Related Questions