Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine Spy to return different values based on argument

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.

like image 667
Andy897 Avatar asked Jun 27 '17 05:06

Andy897


1 Answers

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);
  });
});
like image 92
Winter Soldier Avatar answered Sep 28 '22 06:09

Winter Soldier