dimanche 20 janvier 2019

Testing Observable

I'm reading the German Angular book 'Angular Buch'. Unfortunately the book is based on Angular 4. So some stuff has changed since then.

I tried to get a test running but not sure what's the best way to do this. My updated code looks like this:

describe('BookListService', () => {
  const expectedBooks = [
    new Book('111', 'Book 1', [], new Date()),
    new Book('222', 'Book 1', [], new Date()),
  ];

  let httpStub;

  beforeEach(() => {
    httpStub = {
      get: () => of({

        json: () => expectedBooks
      })
    };

    TestBed.configureTestingModule({
      providers: [
        {
          provide: HttpClient,
          useValue: httpStub
        },
        BookStoreService
      ]
    });
  });

  it('should GET a list of all Books',
    inject([BookStoreService], (service: BookStoreService) => {

      let receivedBook: Book [];
      service.getAll().subscribe(b => receivedBook = b);

      expect(receivedBook.length).toBe(2);
      expect(receivedBook[0].isbn).toBe('111');
      expect(receivedBook[1].isbn).toBe('222');
    }));
});

But I get an error Cannot read property 'length' of undefined. Due to that the Observable is not finished when the assertions check.

Is the best way just to copy past the assertion part inside the Observable callback or are there better ways?

Aucun commentaire:

Enregistrer un commentaire