我有一个具有输入字段的Angular 6组件。如果用户尝试离开时任何输入字段验证失败,则将触发该canDeactivate
功能的守卫。守卫是通用的,因为此逻辑需要在应用程序中的多个组件上发生。它运行得很好,但是当我尝试对这种行为进行单元测试时,canDeactivate
永远无法达到防护中的功能。到达守卫本身,但从未到达功能。我是否以不正确的方式提供警卫?
防护组件接口
export interface GuardComponent {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
可以停用Guard
export class CanDeactivateGuard implements CanDeactivate<GuardComponent> {
constructor() { }
canDeactivate(component: GuardComponent): Observable<boolean> | Promise<boolean> | boolean {
return component.canDeactivate();
}
}
零件
export class MyComponent implements OnInit, GuardComponent {
...
canDeactivate() {
if (!this.form.invalid) {
return true;
}
this.isError = true;
return false;
}
}
规格
const routes = [
{
path: 'my-component',
component: MyComponent,
canDeactivate: [CanDeactivateGuard],
},
{
path: 'my-component-2',
component: MyComponent2
}
];
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ RouterTestingModule.withRoutes(routes) ],
declarations: [ MyComponent, MyComponent2 ],
providers: [ CanDeactivateGuard ],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixutre.componentInstance;
fixture.detectChanges();
});
it('should restrict route change if validation fails', fakeAsync(inject([Router, Location, CanDeactivateGuard], (router: Router, location: Location, guard: CanDeactivateGuard) => {
const textbox = fixture.debugElement.query(By.css('#inputField')).nativeElement;
const canDeactivateSpy = spyOn(guard, 'canDeactivate');
const componentDeactivateSpy = spyOn(component, 'canDeactivate');
// anything lower than 0 will fail the form
textbox.value = '-10';
fixture.detectChanges();
router.navigate(['/my-page-2']).then(() => {
expect(location.path()).toBe('/my-component'); // path doesn't change because guard blocks it due to form being invalid
expect(canDeactivateSpy).toHaveBeenCalled();
expect(componentDeactivateSpy).toHaveBeenCalled();
});
})));
测试失败,因为canDeactivate
从未达到功能。