8

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.

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
Andy897
  • 6,915
  • 11
  • 51
  • 86

1 Answers1

10

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);
  });
});
Winter Soldier
  • 2,607
  • 3
  • 14
  • 18