mardi 12 novembre 2019

How do I test the branches in this Angular Resolver?

Resolver:

export class ItemsLoadGuard implements Resolve<boolean> {
  // Need subscription to check if value has been set
  private itemsSub: Subscription;
  private hasLoaded: boolean;

  constructor(private facade: ItemsFacade) {}

  /**
   * Dispatch action if data is not loaded
   * Return when loading is false
   */
  public resolve(): Observable<boolean> {
    this.hasLoaded = false;
    this.itemsSub = this.facade
        .items$()
        .subscribe(items =>
            !items || items === defaultItemsState.items? this.facade.loadItems() : (this.hasLoaded = true)
        );

    return this.hasLoaded
        ? of(this.hasLoaded)
        : this.facade.loadingItems$().pipe(
              filter(loading => !loading),
              take(1),
              tap(() => this.itemsSub.unsubscribe()),
              map(() => true)
          );
  }
}

My resolver file checks to see if some data is loaded (items) and if it isn't loaded then load the data through a call in the facade.

Once the data is loaded, then return true.

Test file:

describe('ItemsLoadGuard', () => {
  let guard: ItemsLoadGuard;

  beforeEach(() => {
      TestBed.configureTestingModule({
          providers: [ItemsLoadGuard, ItemsFacade, provideMockStore()]
      });

      guard = TestBed.get<ItemsLoadGuard>(ItemsLoadGuard);
  });

  it('should be created', () => {
      expect(guard).toBeTruthy();
  });

  it('should return true if Items are loaded', () => {
      guard.resolve().subscribe(resolve => {
          expect(resolve).toBe(true);
      });
  });
});

I'm unsure how to test the this.itemsSub... statement & the return statement's branches.

Aucun commentaire:

Enregistrer un commentaire