我有一个要测试的组件。测试失败,并显示消息
AdminPanelComponent>应该创建
TypeError:无法读取未定义的属性“角色”
错误属性:对象({ngDebugContext:DebugContext _({视图:Object({def:Object({factory:Function,nodeFlags:50577443,rootNodeFlags:1,nodeMatchedQueries:0,标志:0,节点:[Object({nodeIndex:0,父级:null,renderParent:null,bindingIndex:0,outputIndex:0,checkIndex:0,标志:1,childFlags:50577443,directChildFlags:1,childMatchedQueries:0,matchedQueries:Object({}),matchedQueryIds:0,引用:Object({}),ngContentIndex:null,childCount:11,绑定:[],bindingFlags:0,输出:[],元素:Object({ns:``,name:'div',attrs:[Array],template:null,componentProvider:null,componentView:null,componentRendererType:null,publicProviders:null({}),allProviders:null({}),handleEvent:Function}),provider:null,text:null,查询:null,ngContent:null}),Object({nodeIndex:1,parent:Object({nodeIndex:0,parent:null,renderParent:null,bindingIndex:0,outputIndex:0,checkIndex:0,标志:1,childFlags:50577443,directChildFlags:1,chi ...在在HasRoleDirective.ngOnInit(http://localhost:9876/_karma_webpack_/src/app/_directives/hasRole.directive.ts:16:53)在checkAndUpdateDirectiveInline(http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:26276:1)在checkAndUpdateNodeInline(http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:37133:1)在checkAndUpdateNode(http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:37072:1)在debugCheckAndUpdateNode(http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:38094:36)在debugCheckDirectivesFn(http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:38037:1)在Object.eval [作为updateDirectives](ng:///DynamicTestModule/AdminPanelComponent.ngfactory.js:62:5)在Object.debugUpdateDirectives [作为updateDirectives](http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:38025:1)在checkAndUpdateView(http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:37037:1)在callViewAction(http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:37403:1)
admin-panel.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-admin-panel',
templateUrl: './admin-panel.component.html',
styleUrls: ['./admin-panel.component.css']
})
export class AdminPanelComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
admin-panel.component.html
<div class="container mt-5">
<h2>Admin panel</h2>
<div class="tab-panel">
<tabset class="member-tabset">
<tab heading="User Management" *appHasRole="['Admin']">
<div class="container">
<app-user-management></app-user-management>
</div>
</tab>
<tab heading="Photo management" *appHasRole="['Admin', 'Moderator']">
<app-photo-management></app-photo-management>
</tab>
</tabset>
</div>
</div>
hasRole.directive.ts
import { Directive, Input, ViewContainerRef, TemplateRef, OnInit } from '@angular/core';
import { AuthService } from '../_services/auth.service';
@Directive({
selector: '[appHasRole]'
})
export class HasRoleDirective implements OnInit {
@Input() appHasRole: string[];
isVisible = false;
constructor(private viewContainerRef: ViewContainerRef,
private templateRef: TemplateRef<any>,
private authService: AuthService) { }
ngOnInit() {
const userRoles = this.authService.decodedToken.role as Array<string>;
// if no roles clear the viewContainerRef
if (!userRoles) {
this.viewContainerRef.clear();
}
// if user has role need to render the element
if (this.authService.roleMatch(this.appHasRole)) {
if (!this.isVisible) {
this.isVisible = true;
this.viewContainerRef.createEmbeddedView(this.templateRef);
} else {
this.isVisible = false;
this.viewContainerRef.clear();
}
}
}
}
无法正常工作的代码部分是
const userRoles = this.authService.decodedToken.role as Array<string>;
我如何测试此组件?
测试Angular应用程序的最佳方法是模拟所有需要测试的组件。
最简单的方法是使用类似ng-mocks的库。
尽管如此,您需要像这样对AuthService进行存根]
TestBed.configureTestingModule({ declarations: [HasRoleDirective, AdminPanelComponent], provides: [ { provides: AuthService, useValue: { decodedToken: { role: [], // <- you can put here values for the test }, roleMatch: () => false, // <- or to use a spy here. }, }, ], })
在这种情况下,AuthService将是带有不执行任何操作的伪造方法的存根。