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

153
Vistas
How to test function defined on window object in Jest and typescript

I'm trying to test a call to a function defined on the global window object. I have looked at multiple examples but am still not able to run a simple test case.

Api.ts

import "./global.d";
const verifier = window.Verifier;

export class Api {
  constructor(private readonly id: string) {}
  public fetchData() {
    return new Promise<object>((resolve, reject) => {
      verifier.request({
        request: {
          id: this.id
        },
        onSuccess: (data: object) => {
          resolve(data);
        },
        onFailure: () => {
          reject("Error!");
        }
      });
    });
  }
}

Api.test.ts

import { Api } from "./Api";

let windowSpy: any;

describe("Test Apis", () => {
  beforeEach(() => {
    windowSpy = jest.spyOn(window, "window", "get");
  });

  afterEach(() => {
    windowSpy.mockRestore();
  });
  it("should call the function", () => {
    const mockedReplace = jest.fn();
    windowSpy.mockImplementation(() => ({
      Verifier: {
        request: mockedReplace
      }
    }));
    const api = new Api("123");
    api.fetchData();
    expect(mockedReplace).toHaveBeenCalled();
  });
});

global.d.ts

import { Verifier } from "./verifier";

declare global {
  interface Window {
    Verifier: Verifier;
  }
}

verifier.d.ts

type RequestPayload = {
  request: {
    id: string;
  };
  onSuccess: (data: object) => void;
  onFailure: () => void;
};
type verifyCode = number;

export interface Verifier {
  request: (requestPayload: RequestPayload) => verifyCode;
}

I have also created a codesandbox example for easy reference https://codesandbox.io/s/cranky-mccarthy-2jj622?file=/src/verifier.d.ts

about 4 years ago · Juan Pablo Isaza
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