Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

369
Visualizações
React Testing Library clears hash after click on <a> tag

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Based on this SO, this behavior its more like a jsdom issue. And to accomplish the expected value you should do something like this:

const oldLocation = window.location;

describe("matching cities to foods", () => {

  afterEach(() => {
    // AFTER EACH TEST, set it to the original object.
    window.location = oldLocation;
  });

  test("Test", async () => {
    // delete only for this test
    delete window.location;

    // Change only the hash option and keep the rest same as the original.
    window.location = { ...oldLocation, 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");
  });
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda