jasmine.github.io
jasmine.github.io copied to clipboard
Document use of "originalFn" argument in `createSpy`
The docs for createSpy say that the function takes a second argument called "originalFn" that is described as "Function to act as the real implementation". I thought that might mean that jasmine.createSpy("someFunc", otherFunc) was equivalent to
const spy = jasmine.createSpy("someFunc");
spy.and.callFake(otherFunc)
but this doesn't seem to be the case. If it's not calling through to the "original", why pass an "original" at all?
I can't find any examples of the two-argument version anywhere. It would be helpful to give an example of when this version is desirable.
The "original" function is the function you're spying on... for example:
const spy = jasmine.createSpy("random", Math.random);
spy.and.callThrough();
console.log(spy()); // => random number
Passing an "original" function tells the spy what function it was originally spying on... but doesn't install a stub (that is, unlike spyOn(Math, "random"), it doesn't change the behavior of calling the original Math.random() function).
You're right though, the docs doesn't really make that clear... and I'm not sure if there's any use cases where that would be helpful.
I haven't been using Jasmine for that long (less than a year), so maybe I don't have a good mental model for what's happening here. Is there a difference between my example (using callFake) and yours (using callThrough)? Are there any places other than callThrough that depend on a tracked original / "real" function?
The callFake spy strategy is designed to allow the user to supply a different function to call during the test to allow custom logic. The callThrough spy strategy is there to allow calling through to the real implementation even though a spy is applied. You might do this if you want to track what the code under test is doing, but providing a full mock implementation would be too costly to write.
Realistically, the primary way that createSpy would be called with an originalFn is through spyOn