如何为单元Angular 6组件的测试提供防护措施?

时间:2018-09-25 19:56:45

标签: javascript unit-testing jasmine angular6 angular-router-guards

我有一个具有输入字段的 Angular 6 组件。如果用户尝试导航而输入字段中的任何一个未通过验证,则将触发canDeactivate函数的防护。保护措施是通用的,因为此逻辑需要在应用程序中的多个组件上发生。它可以很好地运行它,但是当我尝试对该行为进行单元测试时,永远都无法实现防护中的canDeactivate函数。到达了警卫本身,但没有到达职能。我是否以错误的方式提供了警卫?

Guard Component Interface

export interface GuardComponent {
    canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

CanDeactivateGuard

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函数,因此测试失败。

0 个答案:

没有答案