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

309
Visualizações
how to spy on window.location functions?

i need to cover my code with some unit tests and in one of then i have the following situation.

app.tsx

           async someMethod(
.
.
.
                window.location.replace(sessionStorage.getItem(REDIRECT_VALUE));
.
.
.
            )

and in my test file

      window.location.replace = jest.fn();
.
.
      somevariable.SomeMethod = jest.fn();

      expect(window.location.replace).toHaveBeenCalledWith("some url to redirect on");

i'm getting the followein error : Cannot assign to read only property 'replace' of object '[object Location]'

i've tried other aproachs like

 backupState = window.location
 delete window.location;
 window.location = Object.assign(new URL("https://example.org"), {
 ancestorOrigins: "",
 replace: jest.fn()
 });

});

but i get different erros for each one of them, is there another way of doing it?

Previously i was using :

history.location.push(sessionStorage.getItem(REDIRECT_VALUE));

and

expect(auth.history.push).toHaveBeenCalled();

and in that case the test went OK.

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

0

One way to test it is:

Create a mock function to location.replace:

const replaceMock = jest.fn();

And spyOn window, replacing location object and setting the replaceMock to replace.

Complete test example:

const replaceMock = jest.fn();

describe('replace Location test ', () => {

  it('should call location with specific arg', () => {
    jest.spyOn(global as any, 'window', 'get').mockImplementationOnce(() => ({
      location: {
        replace: replaceMock,
      },
    }));

    someMethod();

    expect(replaceMock).toBeCalledWith('XX Value you want to test XX');
  });
});
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