我正在尝试为指令创建测试,如果用户没有正确的权限查看该指令,则该指令应清除该指令所附加的元素。我从创建带有伪指令的虚拟组件开始。问题是,当函数是私有的且不带参数时,我不知道该如何测试其功能。我可以得到一些帮助来为此指令创建测试吗?
这里是指令本身,checkRoles
方法只是循环访问权限,并检查另一个数组以查看该数组中是否存在该权限。如果效果良好,则隐藏其附加元素。
import { Directive, Input, OnInit, ViewContainerRef } from '@angular/core';
import { AppService } from '../services/app-service.service';
@Directive({
selector: '[appHasRole]'
})
export class HasRoleDirective implements OnInit {
@Input() appHasRole: string[];
constructor(
private viewContainer: ViewContainerRef,
private appService: AppService
) { }
ngOnInit() {
if (Array.isArray(this.appHasRole)) {
this.checkRoles();
}
}
private checkRoles() {
this.appHasRole.forEach(role => {
if (!this.appService.hasPermission(role)) {
this.removeFromView();
}
});
}
private removeFromView() {
this.viewContainer.clear();
}
}
,这是规格文件。我先创建用户权限,然后再创建所需的权限。老实说,我不知道从这里出发,因为指令上的函数是私有的。
import { HasRoleDirective } from './has-role.directive';
import { Component, DebugElement } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
@Component({
template: `<div [appHasRole]="TEST_ROLE">Testing hasRoleDirective</div>`
})
class TestHasRoleDirective {}
describe('HasRoleDirective', () => {
let component: TestHasRoleDirective;
let fixture: ComponentFixture<TestHasRoleDirective>;
let element: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestHasRoleDirective, HasRoleDirective]
});
fixture = TestBed.createComponent(TestHasRoleDirective);
component = fixture.componentInstance;
element = fixture.debugElement.query(By.css('div'));
});
it('should create an instance', () => {
const directive = HasRoleDirective;
expect(directive).toBeTruthy();
});
it('should hide the element if the user does not have the role', () => {
const userPermissions = ['NOT_TEST_ROLE'];
const neededPermission = ['TEST_ROLE'];
component.appHasRole = neededPermission;
});
});