Angular Component Testing - How to check for a nested element

Discussão em 'Angular' iniciado por chabiya99, Setembro 11, 2024.

  1. chabiya99

    chabiya99 Guest

    This loading-overlay component is used in other components through a service

    <div *ngIf="isLoading$ | async" class="loading-overlay">
    <mat-progress-bar color="accent" mode="indeterminate"></mat-progress-bar>
    </div>


    for example,

    <app-loading-overlay class="special-position"></app-loading-overlay>

    <div class="container">
    <div class="row py-3">
    <div class="col-12 col-md-8 mb-3">
    <mat-card> ...


    like this. And it's called inside components like this

    this.loadingOverlayService.startLoading();
    this.loadingOverlayService.stopLoading();


    using this service

    export class LoadingOverlayService {
    private loading = new BehaviorSubject<boolean>(false);

    // Observable to be used in components
    isLoading$ = this.loading.asObservable();

    startLoading() {
    this.loading.next(true);
    }

    stopLoading() {
    this.loading.next(false);
    }
    }


    It works like it is intended to work, But in this test in spec.ts file

    it('should display loading overlay when loading service is active', () => {
    loadingOverlayService.startLoading();
    fixture.detectChanges();

    const loadingOverlay = fixture.nativeElement.querySelector(
    'app-loading-overlay'
    );
    expect(loadingOverlay).toBeTruthy();
    });

    it('should not display loading overlay when loading service is inactive', () => {

    loadingOverlayService.stopLoading();
    fixture.detectChanges();

    const loadingOverlay = fixture.nativeElement.querySelector('app-loading-overlay');
    expect(loadingOverlay).toBeNull();
    });


    Both cases return true cause I'm directly checking whether the parent component exits. What I want to check is that only .loading-overlay shows when it needs to.

    Basically what I want to check is this loading-overlay class is working correctly with startLoading and stopLoading methods.

    I tried this fixture.debugElement.nativeElement.querySelector('[loading-overlay]'); and bunch of other ways but couldn't figure out

    Continue reading...

Compartilhe esta Página