Using Jasmine to spy on variables in a function

寵の児 提交于 2019-12-18 18:46:26

问题


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 the value of local_a being what it should be (for example in the first line of code)? I'm a bit new to Jasmine, so am stuck. Thanks in advance.


回答1:


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();


来源:https://stackoverflow.com/questions/9619500/using-jasmine-to-spy-on-variables-in-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!