我有一个 Angular 指令,它在它的 onInit 方法中调用授权服务。它看起来像这样:
@Directive({
selector: '[checkRights]'
})
export class RightsDirective implements OnInit{
@Input('checkRights') expectedRights: Right[];
constructor(private _element: ElementRef, private _userService: UserService) {
}
ngOnInit() {
this._userService.hasAnyRights(this.expectedRights).subscribe(hasRights => {
if(hasRights){
this._element.nativeElement.remove();
}
})
}
}
我想测试它,所以我创建了一个测试,它在虚拟组件中设置它:
describe('RightsDirective', () => {
let component: TestRightsDirectiveComponent;
let fixture: ComponentFixture<TestRightsDirectiveComponent>;
let userService: UserService;
let parentElement: DebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TestRightsDirectiveComponent, RightsDirective],
providers: [UserService],
imports: [HttpClientTestingModule]
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestRightsDirectiveComponent);
component = fixture.componentInstance;
parentElement = fixture.debugElement.query(By.css('div'));
userService = TestBed.get(UserService);
});
it('should remove elements when user has no rights to it', async(() => {
spyOn(userService, 'hasAnyRights').and.returnValue(of(false));
expect(parentElement.children.length).toEqual(0);
}));
});
@Component({
template: `<div> <span [checkRights]="['ADMIN']"> </span></div>`
})
class TestRightsDirectiveComponent {
}
现在,我知道这行不通。我知道测试本身存在多个问题,这只是我要检查的一个示例。
我用detectChanges、fakeAsync和tick()s等多次尝试。我花了最后3个小时在上面(这是我第一次测试指令,我对Angular本身很陌生)并检查了谷歌的前4页。
我如何确保: - 在 onInit 启动之前模拟来自服务的响应?- .subscribe() 指令在期望测试之前完成?还有其他我没有看到的问题吗?配置正确吗?