In our single-page application, switching between pages is realized with window.location.hash
. And I found a problem in React Testing Library unit-tests - triggering click on <a/>
tag clears window.location.hash
. For example, when I am on the "Info" page, my hash is equal to '#info'
. And when I click on <a />
element, hash does not change. But in the tests hash becomes an empty string ''
after doing same thing.
Here's a short test that doesn't work:
import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
test('Test', async () => {
window.location.hash = 'hash';
render(<a className="some-class">Some text</a>);
await userEvent.click(screen.getByText('Some text'));
await new Promise(resolve => setTimeout(resolve, 30));
expect(window.location.hash).toEqual('#hash');
});
And here's it error message:
Error: expect(received).toEqual(expected) // deep equality
Expected: "#hash"
Received: ""
The problem is with anchor tag. Test with the span
tag works OK:
import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
test('Test', async () => {
window.location.hash = 'hash';
render(<span className="some-class">Some text</span>); // <span /> instead of <a />
await userEvent.click(screen.getByText('Some text'));
await new Promise(resolve => setTimeout(resolve, 30));
expect(window.location.hash).toEqual('#hash');
});
Question How can I avoid this behavior? I can't just get rid of a
tags in the code, because most of the basic components is declared in another npm library.
EDIT 1 I don't really want to check location.hash
. I want to check page's content, which is depends on location.hash
value. And the real problem is: when location.hash
becomes empty string some of the content disappears.