0

how can I test a function that call a promise ?

click() {
    this.todoService.getUsers().then(
      (resp) => {
        this.users = resp;
      },
      (reject) => {
        console.log(reject);
      }
    );
  }

I tried this , but the console return undeefined

  it('should get all users', () => {
  const users =[....]
    todoServiceSpy.getUsers.and.returnValue(of(users).toPromise());
    component.click();
    console.log('component.users', component.users);

    expect(component.users).toEqual(users);

I'm new in testings

1 Answers1

1

You can use async/fixture.whenStable() to wait for the promises in queue to complete before proceeding.

// add async here
it('should get all users', async () => {
    const users =[....]
    todoServiceSpy.getUsers.and.returnValue(of(users).toPromise());
    component.click();
    
    // !! wait for all promises in queue to complete before proceeding
    await fixture.whenStable();
    console.log('component.users', component.users);
    // do assertions
    expect(component.users).toEqual(users);

You can also use fakeAsync/tick. I suggest you read up on these methodologies.

It explains some of it here: https://www.digitalocean.com/community/tutorials/angular-testing-async-fakeasync.

AliF50
  • 16,947
  • 1
  • 21
  • 37