首页 > 解决方案 > Jasmine AngularJs 如何访问控制器的属性

问题描述

这是我的 AngularJs 代码,我想编写一个单元测试,它应该在控制器函数中调用变量和函数。

例如,我想期待 abcCode 是否是toBeDefined();

请让我知道如何加载模块并调用控制器函数 (abcCodesCntrl) 中的属性。你的建议真的很有帮助。谢谢

功能 () {

angular.module('abcapp',[])
    .component('abcCodes', {
        templateUrl: 'app/abcCodes/abcCodes.html',
        controller: abcCodesCntrl
    })
    .config(function ($stateProvider) {
        $stateProvider
            .state('abcCodes', {
                parent: 'home',
                url: 'abcCodes',
                template: '<abc-codes flex layout="column"></abc-codes>',
                data: {
                    label: "abc Codes",
                    icon: 'business',
                    menu: true
                }
            });
    });

/** @ngInject */
function abcCodesCntrl(F $state, abcCodeSvc, $scope, $mdDialog) {
    var ctrl = this;


    ctrl.abcCodes = [];

    ctrl.loadingabcCodes = false;

} }

标签: angularjsunit-testingjasminekarma-jasmineangularjs-controller

解决方案


beforeEach(() => {
  angular.mock.module('abcapp');
});

it('pass', inject( $rootScope => {
  const scope = $rootScope.$new();
  const element = angular.element('<abc-codes/>');
  const template = $compile(element)(scope);
  const controller = template.controller('abcCodes');
  expect(controller.abcCodes).toBeDefined();
}))

如果你可以使用 es6 而不是控制器成为类

export class abcCodesCntrl{
  /** @ngInject */
  constructor( $state, abcCodeSvc, $scope, $mdDialog) {
    this.$state = $state;
    this.abcCodeSvc = abcCodeSvc;
    this.$scope = $scope;
    this.$mdDialog = $mdDialog;
    this.abcCodes = [];
    this.loadingabcCodes = false;
  }
}

没有太大的改进,但是您可以测试与指令分开的控制器,这意味着您不需要创建和初始化元素。只需测试它自己的功能。同样,只要您添加方法,它就会更容易阅读。


推荐阅读