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

118
Vistas
How to spyOn proxied objects with jest?

There is a scenario where a library exports a proxied object as a public API. Given that the API of the library can't be changed, I failed to find a way how to spyOn a proxied object using jest. Here is an example:

describe("spying on proxied objects with Jest", () => {
    it("should pass", () => {
        const foo = {
            a() {
                return 42;
            }
        };

        const p = new Proxy(foo, {
            get() {
                return () => {
                    return 53;
                };
            }
        });

        const mock = jest.spyOn(foo, "a");
        p.a(); // 53
        expect(mock).toHaveBeenCalled();
    });
});

the test case above fails with:

expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

Any ideas?

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

0

That's because foo.a is actually never called as your proxy doesn't call your target.

This test passes

describe("Foo", () => {
    it("should pass", () => {
      const foo = {
        a() {
          return 42;
        },
      };

      const p = new Proxy(foo, {
        get(target, prop) {
          return () => {
            target[prop]();  /* <-- Calling target */
            return 52;
          };
        },
      });

      const mock = jest.spyOn(foo, "a");
      const result = p.a(); // 52
      expect(mock).toHaveBeenCalled();
    });
  });
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