I have a function that looks something like this:
import {someLibraryMethod} from 'someLibrary';
function setFullWidth(el) {
someLibraryMethod(el);
el.setAttribute('width', '100%');
}
To test this function, I am utilizing Sinon to create a mock element that only supports the setAttribute
method:
const fakeElement = {
setAttribute: sinon.spy()
};
setFullWidth(fakeElement);
assert(fakeElement.setAttribute.calledWithExactly('width', '100%'));
An issue arises when someLibraryMethod
assumes that el
is an HTML element and attempts to invoke other methods on it, such as hasAttribute
. While I could include these as stubs or spies in fakeElement
, I am curious if Sinon offers a way to generate an object that can spy on any method or property access?
For instance:
const fakeElement = sinon.spyOnAnyProperty();
fakeElement.setAttribute(); // valid
fakeElement.hasAttribute(); // valid
fakeElement.foo(); // also valid
// some method to verify which methods were called