'Spying on property changes with Sinon

I am stubbing properties with sinon. I have trouble understanding how the related spying works. Most of the sinon spy methods seem to be related to function calls and not to access of object properties. As a workaround I created a variable for tracking the property access and set it manually when the related getter function is called. See the code example below. This seems to work just fine but I feel like I am probably duplicating some functionality that already exists in sinon. What would be a more idiomatic way of achieving the same result?

      const sinon = require('sinon');
      const lib = require('./lib');
      const app = require('./app');

      const sandbox = sinon.createSandbox();

      let fooAccessed = false;

      sandbox.stub(lib, 'foo').get(() => {
        fooAccessed = true;
        return 123
      });

      app();

      expect(fooAccessed).toEqual(true);


Solution 1:[1]

I know this is probably not the answer you want, because i do not use "sinon", but i will answer anyway. Perhaps this helps you in any way.

You can use a Proxy object to intercept accessing a object.

const obj = {
    foo: "bar",
    baz: true
};

let accessed = false;

const proxied = new Proxy(obj, {
    get(target, prop) {
        if (prop === "foo") {
            accessed = true;
        }
        return target[prop];
    }
});

console.log(proxied, accessed);
console.log(proxied.foo);
console.log(proxied, accessed);

Result:

{ foo: 'bar', baz: true } false
bar
{ foo: 'bar', baz: true } true

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marc