jestjssinon

Check whether stub getter has been called using sinon


I'm trying to check whether a stubbed getter is being called using sinon.

I've simplified my use case as follows:

export class MyClass {
  public method() {
    return 5;
  }

  public get property() {
    return 5;
  }
}

it("stubs getter", () => {
    const myClass = sinon.createStubInstance(MyClass);
    const stub = sinon.stub(myClass, "property").get(() => 10);
    expect(myClass.property).toBe(10); // passes
    expect(stub.called).toBe(true);    // fails
});

The stubbed getter is clearly working, but I can't seem to be able to verify that it has been called and I can't find anything in the documentation that can help.

Sandbox link


Solution

  • This is because you are stubbing the get accessor but you are spying the property itself. Said differently, the property is never called - hence called being false - but its getter is called.

    You should stub the getter and create a spy:

    export class MyClass {
      public method() {
        return 5;
      }
    
      public get property() {
        return 5;
      }
    }
    
    it("stubs getter", () => {
        const myClass = sinon.createStubInstance(MyClass);
        sinon.stub(myClass, "property").get(() => 10);
    
        const spiedGetter = spy(myClass, "property", ["get"]);
    
        expect(myClass.property).toBe(10); // passes
        expect(spiedGetter.called).toBe(true);    // works
    });
    
    

    The spies documentation of sinon explains this behaviour, although arguably not very well:

    https://sinonjs.org/releases/v17/spies/