Jasmine Spy to return different values based on argument

Andy897 picture Andy897 · Jun 27, 2017 · Viewed 8.6k times · Source

I am spying a JS method. I want to return different things based on actual argument to the method. I tried callFake and tried to access arguments using arguments[0] but it says arguments[0] is undefined. Here is the code -

 spyOn(testService, 'testParam').and.callFake(function() {
     var rValue = {};
     if(arguments[0].indexOf("foo") !== -1){
         return rValue;
     }
     else{
         return {1};
     }
 })        

This is suggested here - Any way to modify Jasmine spies based on arguments?

But it does not work for me.

Answer

Winter Soldier picture Winter Soldier · Jun 27, 2017

Use of arguments should work just fine. Also on a side note could you paste your entire object under test- though that's not the source of the issue.

Here is how I used it. See it in action here

var testObj = {
  'sample': "This is a sample string",
  'methodUnderTest': function(param) {
    console.log(param);
    return param;
  }
};

testObj.methodUnderTest("You'll notice this string on console");

describe('dummy Test Suite', function() {
  it('test param passed in', function() {
    spyOn(testObj, 'methodUnderTest').and.callFake(function() {
      var param = arguments[0];
      if (param === 5) {
        return "five";
      }
      return param;
    });
    var val = testObj.methodUnderTest(5);
    expect(val).toEqual('five');
    var message = "This string is not printed on console";
    val = testObj.methodUnderTest(message);
    expect(val).toEqual(message);
  });
});