So, let mySpy = spyOn(service, 'myMethod').and.stub()
is the exact same as let mySpy = spyOn(service, 'myMethod')
. Both of these do the same 2 things:
1 - they will wait until that function is called and can report back on it later and tell you if it was called via expect(mySpy).toHaveBeenCalled()
.
2 - they intercept the function and NEVER call it. So if you spy on a function, it doesn't actually get called. Which is extremely useful when paired with let mySpy = spyOn(service, 'myMethod').and.returnValue(someUsefulReturnValue)
.
However, as a side note, in some situations you want to spy on a function to see if it was called, write an expectation that it was called, BUT actually allow it to get called, which is when you would use let mySpy = spyOn(service, 'myMethod').and.callThrough()
Whereas, let mySpy = spyOn(service, 'myMethod').and.callFake()
does the same 2 things in the bullet points above, except with one benefit. You can call a function inside of callFake()
that will execute inside of myMethod
. I find this is not extremely useful when following programming principles, and is used less often.
I.e. let mySpy = spyOn(service, 'myMethod').and.callFake(() => { this.somethingThatNeedsToBeUpdated = somethingUseful; })
stub()
method; however, there is no method signature for stub that accepts a parameter. That is the first hint. – Bentz