如何测试 returns 一个 promise $q 的函数?

How to test a function which returns a promise $q?

我的 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 is not a function"

知道我在这里遗漏了什么吗?

您的 urlLaunch 函数应该 return 一个承诺,但您用一个 return 什么都没有的假函数来模拟它。所以使用 returned promise 的代码实际上会收到 undefined。那不行。

您需要 return 间谍函数的承诺:

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

// ...