如何测试返回promise $ q的函数?

时间:2017-03-13 11:13:11

标签: angularjs jasmine karma-runner

我的JS文件:

case "launch": helper.urlLaunch("http://www.google.com").then(function (){start();});

urlLaunch的定义

urlLaunch: function (url) {
            //...
            return $q.when();
        },

单元测试

it("should test helper launch url", function() {
            spyOn(helper, "urlLaunch").and.callFake(function(){});
            mySvc.purchase( Url: PURCHASE_URL }); //this calls the "launch" case given above
            $httpBackend.flush();
            expect(helper.urlLaunch).toHaveBeenCalled();
        });

但是这给了我一个错误“TypeError:plan.apply不是函数”

任何想法我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

你的urlLaunch函数应该返回一个promise,但你用一个不返回任何东西的假函数来模拟它。因此,使用返回的promise的代码实际上会收到undefined。那不行。

您需要从间谍函数返回一个承诺:

spyOn(helper, "urlLaunch").and.returnValue($q.when('some fake result'));
mySvc.purchase( Url: PURCHASE_URL });
$scope.$apply(); // to actually resolve the fake promise, and trigger the call of the callbacks

// ...