spy arguments list reflects current state of objects and does not reflect the state of objects from when the spy was called
Describe the bug The spy arguments list reflects current state of objects and does not reflect the state of objects from when the spy was called. Is this intentional and an occupational hazard or is there a way around this behaviour?
To Reproduce Steps to reproduce the behavior:
const obj = {
fn: (input) => {}
};
const stub = sinon.stub(obj, 'fn');
const arg = {
value: 1
}
obj.fn(arg);
arg.value = 2
obj.fn(arg);
console.log(stub.firstCall.args); // output: [ { value: 2 } ] . expected: [ {value: 1 }]
Expected behavior Spy argument lists to contain the state of the object from when the spy was actually called
- Library version: 8.1.1
Hi, @dannymarsland, and thanks for creating the issue.
Giving you the argument by reference and not by value is by design.
The spy gives you the argument with which the function was called. It does not do time travel. It is the object, not the object as it was at any given time, as representing a snapshot of that object varies from use-case to use-case. Deep cloning all objects would both be wasteful, usually not what people want and also entails surprises of their own. What value would a snapshot of an object with a circular reference look like, for instance? Or a snapshot of an object that was created using the module pattern? Some of these things have no correct answer.
If you want some kind of snapshotting functionality you need to implement this yourself by using the stub or fake interface with a custom stub. Something like this:
function createFakeWithArgumentSnapshots(){
const clone = (argument) JSON.parse(JSON.stringify(argument));
const fake = sinon.fake((arg) {
/* Simplified to only handle a single argument. Expand as necessary by using `arguments` */
fake.callSnapshots.push(clone(arg));
});
fake.callSnapshots= [];
return fake;
}
const myFake = createFakeWithArgumentSnapshots();
sinon.replace(obj, 'fn', myFake);
....
console.log(myFake.callSnapshots[0])
What you are experiencing is the by-product of working with mutable state and modifying objects after giving them to other parts of the program. You might want to look into functional programming for alternative ways of achieving the same. Alternatively you could wrap your objects in Object.freeze() if you are certain they should never be modified and want to make sure.