jeudi 14 novembre 2019

Sinon - spy to wrap *any* property access on object

I have a function that looks roughly like this:

import {someLibraryMethod} from 'someLibrary';

function setFullWidth(el) {
  someLibraryMethod(el);
  el.setAttribute('width', '100%');
}

I'm testing this function by using Sinon to create a mock element that only supports setAttribute:

const fakeElement = {
  setAttribute: sinon.spy()
};
setFullWidth(fakeElement);
assert(fakeElement.setAttribute.calledWithExactly('width', '100%'));

The problem is that someLibraryMethod assumets el is an HTML element and tries to call some other methods on it, such as hasAttribute. I could add these as stubs or spies to fakeElement too, but I was wondering if Sinon has a way to create an object that will spy on any method or property access on it?

Something like:

const fakeElement = sinon.spyOnAnyPropety();
fakeElement.setAttribute(); // valid
fakeElement.hasAttribute(); // valid
fakeElement.foo(); // also valid
// some way to check which methods were called

Aucun commentaire:

Enregistrer un commentaire