Stubbing ES6 class fields with sinon (solving "Cannot stub non-existent property" / "Property does not exist!")

218 Views Asked by At

I have a class:

class Foo {
  baz = 3;

  bar() {
    return 5;
  }
}

I am able to stub bar() both on an instance and on the class itself:

  describe("#bar", function() {
    it("can be stubbed on an instance to return 25", function() {
      const foo = new Foo();
      sinon.stub(foo, "bar").returns(25);
      expect(foo.bar()).to.equal(25);
    })

    it("can be stubbed on the class to return 30", function () {
      sinon.stub(Foo.prototype, "bar").returns(30);
      const foo = new Foo();
      expect(foo.bar()).to.equal(30);
    })
  })

However, when I try with a field:

  describe("property baz", function() { 
    it("can be stubbed on an instance to equal 9", function() {
      const foo = new Foo();
      sinon.stub(foo, "baz").value(9);
      expect(foo.baz).to.equal(9);
    })

    it("can be stubbed on the class to equal 12", function() {
      sinon.stub(Foo.prototype, "baz").value(12);
      const foo = new Foo();
      expect(foo.baz).to.equal(12);
    })
  })

The second test fails with:

TypeError: Cannot stub non-existent property baz

I've found questions on here about stubbing properties of objects, but I've not seen anyone address this specific issue.

Ideally, I'd use createSubInstance and just fill in my own fake fields and methods, but that gives me a variant of the same problem:

    it("can be faked on a stub instance", function() {
      const foo = sinon.createStubInstance(Foo, {
        baz: 12,
      });
      expect(foo.baz).to.equal(12);
    })

This errors with:

Error: Cannot stub baz. Property does not exist!
1

There are 1 best solutions below

0
Lin Du On

baz is a Public instance fields

Public instance fields exist on every created instance of a class

baz does not exist on Foo.prototype and you are trying to stub it. that's why you got the error:

TypeError: Cannot stub non-existent own property baz