How to spyOn proxied objects with jest?

Viewed 108

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?

1 Answers

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();
    });
  });
Related