angularjs - 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;
} }
解决方案
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;
}
}
没有太大的改进,但是您可以测试与指令分开的控制器,这意味着您不需要创建和初始化元素。只需测试它自己的功能。同样,只要您添加方法,它就会更容易阅读。
推荐阅读
- c# - 如何在 oledb 连接的 C# 脚本任务中测试数据库可用性
- python - 为主题建模 (LDA) 计算最佳主题数
- javascript - 如何使用 Rollup 构建自定义引导包
- laravel - 如何用 morphMany 链接调用 hasOne?
- java - 构造函数 Point(double, double) 未定义
- python-3.x - 如何从数组中拆分多个项目并将它们添加到python中的另一个数组中?
- sql-server - 按年份查询客户、采购总额、给予客户的总折扣
- elasticsearch - ElasticSearch - 嵌套字段的聚合以返回存储桶中的附加字段
- python - 烧瓶中的简单 python API 问题。尝试创建一个 post 方法将 json 数据添加到列表中
- java - Log4j2 无法发送邮件