简体   繁体   中英

Angular 9 + jest : unit test, mock a promise and check method called then

I need help, I don't know how to mock a promise and check a method is called after in the then() part.

My code looks like this, when I click on the save button of my form :

// File : myComponent.ts
save() {
   const myObject = new MyObject({field: this.form.value.field});

   this.myService.saveObject(myObject).then(() => { // I'd like to mock this
     this.closeDialog(true);
  }, error => {
     this.otherFunction(error);
  });
}


// File : myService.ts
saveOject(myObject: MyObject): Promise<any> {
  return this.myApi.save(myOject).toPromise().then(res => res);
}


// File : myApi.ts
save(myObject: MyObject) {
  return this.http.post('url, myObject);
}

I'm trying to test this function and I would like to mock (or stub ? I don't know the difference) the saveObject function for when the promise is resolved, and the case it's not.

My actuel test file looks like this:

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let myService: MyService;

  beforeEach(async (() => {
     TestBed.configureTestingModule(
   ).compileComponents();

   myService = TestBed.inject(MyService);
  }

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    spyOn(myService, 'saveOject').and.returnValue(new Promise(resolve => resolve()));
  });

  it('should call closeDialog method when save form is successful', () => {
     const spyCloseDialog = jest.spyOn(component, 'closeDialog');

     component.save();
     fixture.detectChanges(); // It's a test, I don't know if it's useful
     expect(spyCloseDialog).toHaveBeenCalledTimes(1); // It's 0 because I don't know how to be in the then part of my function
  });

}

Can somebody help me ? Sincerely

There are two options to choose from:
1) use fakeAsync , for example:

it('should call closeDialog method when save form is successful', fakeAsync(() => {
     const spyCloseDialog = jest.spyOn(component, 'closeDialog');

     component.save();
     tick(50);
     expect(spyCloseDialog).toHaveBeenCalledTimes(1);
}));

2) put your expect inside then , for example

component.save().then(() => expect(spyCloseDialog).toHaveBeenCalledTimes(1)); 

In your test you should import HttpClientTestingModule , so that test runs succesfully and no error is thrown when angular tries to fire up a http call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM