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

195
Vistas
How to mock "window" with jest for Fullstory

I have a function like so, and I just cannot wrap my head around how to mock this use case. I was given the function this way, so I'm not sure I can change it unless there's just a much better way.

Function to test - window is global, so no need to pass in

getWindowNamespace() {
    if (!window.namespace) {
        return false;
    }
    return window[window.namespace];
}

It's like the same window object is being used as two different types and it's really throwing me.

Testing logic I have so far (only relevant code so this wouldn't run as is, but I can provide more information as needed. Right now, I'm able to test the first negative case, but not the final return line.

const mockWindow = (namespace) => {
    global.window = Object.create(window);
    Object.defineProperty(window, 'window', {
        value: {
            namespace: namespace,
        },
        enumerable: true,
        configurable: true,
        writable: true,
    });
    window[namespace] = {};
    window[namespace].log = jest.fn();
}

Maybe I need to create the window as an array instead? Define value differently within defineProperty?

Thank you in advance for any help!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You may need to spyOn global.window.get and return a namespace and the data which window[window.namespace] will be returned

this will allow you to return and mock value for global.window


describe('test', () => {
    jest.spyOn(global, 'window', 'get').mockImplementation(() => ({
        namespace: 'test1',
        test1: 'value' // <<< this is the custom field value depend on whatever namespace is
    }))
    it('should return false', () => {
        expect(getWindowNamespace()).toBe('value');
    });
})
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