业力-茉莉花:预期未定义定义 + 控制器 + 服务



我正在尝试在控制器上运行单元测试,但遇到以下错误:

Expected undefined to be defined.

我知道什么是未定义的,但我不知道为什么它是未定义的以及如何解决它。让我粘贴我的代码以便更好地理解。

控制器

angular
    .module("app.licensing", [])
    .controller("LicensingController", LicensingController)
    LicensingController.$inject = ["textService"];
    function LicensingController(textService) {
        var vm = this;
        vm.licForm = {
            accountName: null,
            ticketNo: null
        };
        vm.controlLabels = textService.licensing.controlLabels;
    }

textService 文本服务基本上只包含字符串的对象并返回一个对象。

(function () {
    "use strict";
    angular
        .module('app')
        .factory("textService", textService)
    function textService() {
        return {
            //Object for Licensing Module
            licensing: {
                pageTitle: "Page Title",
                controlLabels: {
                    accountName: "Account Name",
                    ticketNo: "Ticket No",
                    hostId: "Host Id",
                }
            }
        };
    }
})();

单元测试

describe("-----> LicensingController", function () {
    var LicensingController;
    var textService;
    beforeEach(angular.mock.module("app.licensing"));
    beforeEach(function () {
        module(function ($provide) {
            $provide.value("textService", textService);
        });
    });
    beforeEach(inject(function (_$controller_) {
        LicensingController = _$controller_("LicensingController", {
        });
    }));
    describe("-----> Licensing Form", function () {
        it("--> License Controller should be Defined.", function () {
            expect(LicensingController).toBeDefined();
        });
        it("--> 'licForm' Object must be Defined.", function () {
            expect(LicensingController.licForm).toBeDefined();
        });
        it("--> 'controlLabels' Object must be Defined.", function () {
            expect(LicensingController.controlLabels).toBeDefined();
        });
    });
});
  • 在单元测试中,第三个测试(控件标签(触发错误。在这里,控件标签是未定义的。是因为值来自文本服务吗?
  • 但是为什么它是未定义的以及如何解决这个问题。
  • 任何帮助将不胜感激。

您没有将模拟textService注入beforeEach中的LicensingController中。 添加它,它应该开始工作。

beforeEach(inject(function (_$controller_, _textService_) {    
    LicensingController = _$controller_("LicensingController", { textService: _textService_ });
}));

您还需要删除第二个beforeEach或至少在其中提供textService的模拟实现。

beforeEach(angular.mock.module(function($provide) { 
    $provide.service('textService', function () {
        return {
          //Object for Licensing Module
          licensing: {
            pageTitle: "Page Title",
            controlLabels: {
              accountName: "Account Name",
              ticketNo: "Ticket No",
              hostId: "Host Id",
            }
          }
      };
    });
}));

最新更新