Using Jasmine to spy on variables in a function

后端 未结 1 508
遇见更好的自我
遇见更好的自我 2021-01-03 21:45

Suppose I have a function as follows

function fun1(a) {
  var local_a = a;
  local_a += 5;
  return local_a/2;
}

Is there a way to test for

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-03 22:42

    Not really. You can do the following though:

    Test the result of fun1():

    expect(fun1(5)).toEqual(5);
    

    Make sure it's actually called (useful if it happens through events) and also test the result:

    var spy = jasmine.createSpy(window, 'fun1').andCallThrough();
    fire_event_calling_fun1();
    expect(spy).toHaveBeenCalled();
    expect(some_condition);
    

    Really reproduce the whole function inspecting intermediate results:

    var spy = jasmine.createSpy(window, 'fun1').andCallFake(function (a) {
      var local_a = a;
      expect(local_a).toEqual(a);
      local_a += 5;
      expect(local_a).toEqual(a+5);
      return local_a/2;
    });
    fun1(42);
    expect(spy).toHaveBeenCalled();
    

    0 讨论(0)
提交回复
热议问题