Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!