Jasmine CallFake 101 or for dummies

790 views
Skip to first unread message

Rodrigo

unread,
Sep 4, 2016, 2:35:00 PM9/4/16
to Jasmine
Hi,

I'm starting with Jasmine and I quite don't understand the use of callFake.

In the official Jasmine docs this is what appears:

foo = {
     
setBar: function(value) {
       
bar = value;
     
},
     
getBar: function() {
       
return bar;
     
}
spyOn(foo, "getBar").and.callFake(function(arguments, can, be, received) {
     
return 1001;
});

foo.setBar(123);
fetchedBar = foo.getBar();

Where foo is the object and getBar the method being spied. So far so good. Then a function is passed as the argument in order to call the function in the callFake parameter instead of the actual getBar method. The callFake function will return 1001 when called, no matter what. Then we can read this:

it("when called returns the requested value", function() {
   
expect(fetchedBar).toEqual(1001);
 
});

What I can't understand is: In which scenario I can expect the function to not return 1001?. getbar is being replaced by the function passed in callFake, which will return 1001 every time it's called in that specific spec.

For what I can see, this is equivalent to this:

var a;

a
= function(word){
  console
.log(word);// logs the word into the console
};

a
("Hi didly ho!!");//Hi didly ho!!

a
= function(word){
  alert
(word);
}
a
("shut up flanders");// alert

a
("okily dokily!!")//alert

The first time the function will log the string, the second and third time it will create an alert. I can't expect the function to log the string in the console any more.

I'm sorry if the question seems dumb, but I can get my head around it. Hopefully someone could point out a more realistic scenario that makes it more clear.

Thanks,
Rodrigo.

Gregg Van Hove

unread,
Sep 4, 2016, 9:13:52 PM9/4/16
to jasmi...@googlegroups.com
You are correct. The goal is actually to allow some kind of fake implementation, like a `switch` statement based on an argument or the current call count, for a function that might be called more than once during the execution of a spec. 

Hope this helps. Thanks for using Jasmine!

- Gregg 
--
You received this message because you are subscribed to the Google Groups "Jasmine" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jasmine-js+unsubscribe@googlegroups.com.
To post to this group, send email to jasmi...@googlegroups.com.
Visit this group at https://groups.google.com/group/jasmine-js.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages