Karma-Jasmine:预期未定义定义+控制器+服务

时间:2018-04-11 20:50:29

标签: javascript angularjs karma-jasmine

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

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 Text Service基本上只包含字符串的Object并返回一个Object。

(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();
        });
    });
});
  • 在单元测试中,第3次测试(controlLabels)正在触发错误。这里,controlLabels未定义。是因为价值来自textService吗?
  • 但为什么它未定义以及如何解决。
  • 非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您没有在textService的{​​{1}}中注入模拟LicensingController。添加它,它应该开始工作。

beforeEach

您还需要删除第二个beforeEach(inject(function (_$controller_, _textService_) { LicensingController = _$controller_("LicensingController", { textService: _textService_ }); })); 或至少在其中提供beforeEach的模拟实现。

textService
相关问题