如何使用Restma作为依赖项测试角度模块,使用Karma / Jasmine

时间:2015-12-07 22:10:27

标签: angularjs unit-testing jasmine karma-jasmine restangular

我有一个名为广告系列服务的模块,我已将其剥离为骨头但仍无法使其正常工作

'use strict';

angular.module('CampaignService', []).factory('CampaignService', ['$rootScope', '$q', 'Restangular', 'notifications', function ($rootScope, $q, Restangular, notifications) {


    // Private methods.
    function getCampaignsForCstandUser(successCallbackFcn) {
        // defer
        var listDeferred = $q.defer();
        //load
        Restangular.all('campaigns/cstand/' + $rootScope.loggedInUserId).getList().then(function (result) {
            // resolve
            listDeferred.resolve(successCallbackFcn(result));
        }, function (error) {
            // show an error
            notifications.showError('Error while trying to load campaigns. Error:\n' + error);
        });

        return listDeferred.promise;
    };

    // We now return a public API for our service.
    return {
        getCampaignsForCstandUser: getCampaignsForCstandUser
    };
}]);

这是单元测试文件

"use strict";

/*
 * Unit tests for js/service/campaignService.js
 */

    beforeEach(module("CampaignService"));
    beforeEach(module("Restangular"));

    var CampaignService;
    beforeEach(
        inject(function (_CampaignService_) {
                CampaignService = _CampaignService_;
            }
        ));

    describe("main test", function () {
        it("main test", function () {
            expect(CampaignService.getCampaignsForCstandUser()).toBe(true);
        });
    });
});

在我包含beforeEach(模块(" restangular"))之前,一切似乎都有效;

1 个答案:

答案 0 :(得分:-1)

要测试您的API调用,您应该尝试使用angularJs附带的$ httpService。

我附上官方文档,向您解释此服务的工作原理,并向您展示一些简单的示例: official documentation