lundi 28 décembre 2020

Angular 2 integration Observable that is consumed by html testing

Problem Component have infinite loading screen. How to trigger observable to complete?

In service I have simple method that returns observable from http GET request

This methods reference is assigned for rentalPoints$

And later consumed by html component by using async pipe. And loading indicator is displayed while loading.

Component.ts

ngOnInit(): void {
    // Storing observable with rental points
    this.rentalPoints$ = this.rentalPointService.getRentalPoints();
}

Component.html

 <ng-container *ngIf="rentalPoints$ | async as rentalPoints; else loading">
    <div class="points">
        <h4></h4>
    </div>
</ng-container>

<ng-template #loading>
    <div class="text-center h4">
        <i class="fas fa-spinner fa-spin"></i>
    </div>
</ng-template>

Test component

// Creating mocked cabinet service
const RentalPointServiceStub = {
    // Creating method for cabinet mocked service
    getRentalPoints() {
        // Returning observable with loyalty points information
        return scheduled([{
            pendingAmount: 1,
            availableAmount: 2
        }]
        , asyncScheduler);
    }
};

    describe('RentalPointsComponent', () => {
        // Declaring test variables
        let component: RentalPointsComponent;
        let fixture: ComponentFixture<RentalPointsComponent>;
        let debugElement: DebugElement;
        let nativeElement: any;

    // Setting up Test Bed ( Testing envirement )
    beforeEach(async () => {
        TestBed.configureTestingModule({
            imports: [
            ],
            providers: [
                { provide: RentalPointsService, useValue: RentalPointServiceStub },
            ],
            declarations: [
                RentalPointsComponent,
            ]
        }).compileComponents();
    });

    // Reseting variables each test
    beforeEach(() => {
        fixture = TestBed.createComponent(RentalPointsComponent);
        component = fixture.componentInstance;
        debugElement = fixture.debugElement;
        nativeElement = debugElement.nativeElement;
        fixture.detectChanges();
    });

       it('should show indicator while loading, and render view after', fakeAsync(() => {
        expect(debugElement.query(By.css('.fa-spinner')).nativeElement).toBeTruthy();
        tick(50000); // doesnt finish observable
        flush();  // doesnt finish observable
        fixture.detectChanges();
        // expect(nativeElement.query(By.css('.points')));
    }));
});

Aucun commentaire:

Enregistrer un commentaire