There are a lot of people face the problem of stubing functions with sinon.js doesn't work when using destructor
and there is a great explantion mentioned on Sinon stub function used with destructuring.
And as mentioned in the answer, when using the destructor we call always the original function:
const stub = (o, method) => (o[method] = () => "I am a stub");
const obj = {
methodFoo() {
return "I am foo";
}
};
// same as doing `const methodFoo = obj.methodFoo;`
const { methodFoo } = obj; // "import" using destructuring
console.log("obj.methodFoo(): ", obj.methodFoo());
console.log("methodFoo()", methodFoo());
console.log("Stubbing out method!");
stub(obj, "methodFoo");
console.log("obj.methodFoo: ", obj.methodFoo());
console.log("methodFoo()", methodFoo());
I searched for an answer why the destructor
overrides the stub
or how it works under the hood to understand how to manipulate data but I didn't get any solution. Is there any details about this issue ?
Stubbing overrides the methods property. If you take this contrived example:
const obj = { prop: "value" };
const prop = obj.prop; // or { prop } = obj;
obj.prop = "new value"; // stub()
console.log(prop); // "value"
then it might become clearer. Think of methods as values that can be copied (actually a reference to them gets copied).