Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
Test if the windows location is correctly set

I am setting windows location in my useEffect hook as follows.

const MyComponent = (name) => {
  React.useEffect(() => {
    window.location.href = `/${name}/mypath${window.location.search}`
  }, []);

  return <Fragment/>;
};

I am looking to test that the href value matches correctly.

Thus I am mocking the data as follows and expecting the value to match following String.

www.test.com/name/mypath?param=1

But I end up with error saying that the window.location.href's value is actually the following.

/[object Object]/mypath?param=1

It is missing the host and also not capturing the name prop's value in the href. Could I get some advice on what I doing wrong? Thanks.

My test as follows.

jest.spyOn(React, 'useEffect').mockImplementation(f => f());

delete window.location;
window = Object.create(window);
const host = "www.test.com";
const search = '?param=1'
Object.defineProperty(window, "location", {
  value: {
    host,
    search
  },
  writable: true
});

describe('My tests', () => {
  const render = () => shallow(
    <MyComponent name='name' />
  );

  it('should pass', () => {
    const rendered = render();
    const url = 'www.test.com/name/mypath?param=1';
    expect(window.location.href).toEqual(url);
  });
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You forgot to destructure the props argument for your component,

It should be

const MyComponent = ({name}) => {
//rest of your code

}

The reason is component functions receive only one argument, which is an object with all the props you passed. What you did is just called it name. What I did is destructure the name property from the props object, i.e. took the value that was passed in the name prop

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda