Reputation: 973
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);
Upvotes: 1
Views: 588
Reputation: 1321
Here's an idiomatic way to achieve a similar result:
fooSpy = sinon.spy(lib, 'foo', ['get']);
then
expect(fooSpy.get).to.have.been.called;
Similarly for setters, e.g:
fooSpy = sinon.spy(lib, 'foo', ['set']);
then
expect(fooSpy.set).to.have.been.called;
or even
expect(fooSpy.set).to.have.been.calledWith(appropriate_value_here);
Upvotes: 0
Reputation: 3904
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
Upvotes: 0