【问题标题】:How to test an angular module with Restangular as a dependency, using Karma/Jasmine如何使用 Karma/Jasmine 测试以 Restangular 作为依赖项的 Angular 模块
【发布时间】:2015-12-07 22:10:26
【问题描述】:

我有一个名为活动服务的模块,我已经将它剥离到了最基本的部分,但仍然无法让它工作

'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(module("restangular")); 之前,一切似乎都正常运行

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-02-24
      • 2016-02-26
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 2016-04-16
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多