admin管理员组

文章数量:1122832

I have a code where I invoke a loader when data is loading. I want to test the loader while the data is loading. I want to use fakeAsync for this purpose. However, I am receiving the following message:

Message: Expected one matching request for criteria "Match URL: ;, found none.

import { Component, inject } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AsyncPipe } from '@angular/common';

export interface ProductModel {
  readonly id: number;
  readonly title: string;
  readonly price: number;
}

@Component({
  selector: 'app-root',
  template: `
  <div class="container">
    <h1>Product List</h1>
    @if(products$|async ;as products){
      <ul class="list-group-flush">
        @for(product of products; track product){
          <li class="list-group-item active">
            {{product.title}} {{product.price}}$
          </li>
        }
      </ul>
    }
    @else{
      <div class="spinner-border text-primary" role="status"></div>
    } 
  </div>
`,
  standalone: true,
  imports: [HttpClientModule, AsyncPipe],
})
export class AppComponent {
  httpClient: HttpClient = inject(HttpClient);

  products$: Observable<ProductModel[]> = this.httpClient.get<ProductModel[]>(
    ''
  );
}
describe('AppComponent', () => {
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, AppComponent],
    });

    httpTestingController = TestBed.inject(HttpTestingController);
  });

  afterEach(() => {
    httpTestingController.verify();
  });

  it('should display loader while data is loading', fakeAsync(() => {
    const fixture = TestBed.createComponent(AppComponent);

    fixture.detectChanges();


    let loader = fixture.nativeElement.querySelector('.spinner-border');
    expect(loader).toBeTruthy(); 


    const req = httpTestingController.expectOne('');
    expect(req.request.method).toBe('GET');


    tick(2000);


    req.flush([
      { id: 1, title: 'Product 1', price: 10.99 },
      { id: 2, title: 'Product 2', price: 20.99 },
    ]);

    fixture.detectChanges(); 

    loader = fixture.nativeElement.querySelector('.spinner-border');
    expect(loader).toBeFalsy();

    const productItems = fixture.nativeElement.querySelectorAll('li.list-group-item');
    expect(productItems.length).toBe(2);
    expect(productItems[0].textContent).toContain('Product 1 10.99$');
    expect(productItems[1].textContent).toContain('Product 2 20.99$');
  }));
});

本文标签: jestjsTest loading state angularStack Overflow