Angular JS服务单元测试中的方法未定义

时间:2016-11-22 15:09:27

标签: angularjs jasmine

我正在为现有的AngularJS应用编写单元测试。这项服务只有四种方法。我能够让getFollowUpList工作,但是refresh()不起作用,这是一个非常简单的方法。

刷新方法应该只设置deferredGetFollowUpList = null并在我的测试中返回true。

我得到的错误是:TypeError: Cannot read property 'then' of undefined,所以我的刷新方法未定义。为什么会这样?感谢

服务

(function () {
   "use strict";

   angular
      .module("all.patient.details")
      .factory("followUpListService", ["$rootScope", "$http", "userContext", "$q", "$uibModal", "htmlBaseUrl", FollowUpListService]);

   function FollowUpListService($rootScope, $http, userContext, $q, $uibModal, htmlBaseUrl) {
      var deferredGetFollowUpList = null;

      return {
         getFollowUpList: getFollowUpList,
         displayModal: displayModal,
         refresh: refresh,
         save: save
      }

      function refresh() {
         deferredGetFollowUpList = null;
      }
   }
})();

单元测试

describe("followUpListService", function () {

    beforeEach(module("all.patient.details"));
    var followUpListService = {};
    var $httpBackend;
    var htmlBaseUrlMock;
    var returnedFollowUpListData;
    var deferredGetFollowUpList;
    var $rootScope;
    var $q;
    var $uibModal;

    beforeEach(function () {

        htmlBaseUrlMock = { format: function () { } };     

        module(function ($provide) {
            $provide.value("htmlBaseUrl", htmlBaseUrlMock);
        });

        inject(function (_$rootScope_, _$httpBackend_, _$q_, _$uibModal_, _followUpListService_) {
            $rootScope = _$rootScope_;
            $httpBackend = _$httpBackend_;
            $q = _$q_;
            $uibModal = _$uibModal_;
            followUpListService = _followUpListService_;          
        });

    });

    afterEach(function () {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it("calls refresh()", function () {

        followUpListService.refresh()
        .then(function (data) {
            deferredGetFollowUpList = data;
        });

        expect(deferredGetFollowUpList).toBe(null);
    });

1 个答案:

答案 0 :(得分:0)

由于deferredGetFollowUpList是服务水平变量,您能否将测试编写为 -

followUpListService.deferredGetFollowUpList = data; //Any Mock Data
followUpListService.refresh();
expect(followUpListService.deferredGetFollowUpList).toBe(null);