AngularJS测试:Jasmine模拟回调

时间:2015-03-17 17:19:01

标签: angularjs testing callback jasmine

我有基本的角度JS知识,但我对Jasmine单元测试很新。 我的问题如下:

我需要测试服务方法(来自myService的方法):

myService.method = function(args)
{
    var parameter = "myParam";
    anotherService.anotherMethod(parameter, function(result)
    {
        //Stuff to test using result
        if(result == "blabla")
            testFunction("param");

    });
};

如何模拟anotherService.anotherMethod返回结果并测试myService.method的其余部分?我需要检查一下,例如testFunction是用“param”调用的(使用expect(myFunction)toHaveBeenCalledWith(“param”))。

Thansk的帮助

2 个答案:

答案 0 :(得分:4)

我想要做的是为我的AJAX调用创建一个假函数并使用它的一个参数:

spyOn(anotherService, 'anotherMethod').and.CallFake(function(){
  //Get args : fake result of AJAX call and callback
  var fakeResult = arguments[0];
  var callback = arguments[1];
  return callback(fakeResult);
});

答案 1 :(得分:1)

你可以和Jasmine Spies一起玩,但我建议使用Sinon,因为它支持更多的功能。

此处的文档位于:Sinon

如果你没有使用Sinon的自由,这里有一个Jasmine Spy备忘单: Jasmine Spy Cheatsheet。正如本文所述,

var testPerson = new Person();
spyOn(testPerson, "getName");
testPerson.toString();
expect(testPerson.getName).toHaveBeenCalledWith("param");