title: Angular 9 + jest : unit test, mock a promise and check method called then
body: <p>I need help, I don't know how to mock a promise and check a method is called after in the then() part. </p>
  
  <p>My code looks like this, when I click on the save button of my form :</p>
  
  <pre><code>// File : myComponent.ts
  save() {
     const myObject = new MyObject({field: this.form.value.field});
  
     this.myService.saveObject(myObject).then(() =&gt; { // I'd like to mock this
       this.closeDialog(true);
    }, error =&gt; {
       this.otherFunction(error);
    });
  }
  
  
  // File : myService.ts
  saveOject(myObject: MyObject): Promise&lt;any&gt; {
    return this.myApi.save(myOject).toPromise().then(res =&gt; res);
  }
  
  
  // File : myApi.ts
  save(myObject: MyObject) {
    return this.http.post('url, myObject);
  }
  </code></pre>
  
  <p>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. </p>
  
  <p>My actuel test file looks like this: </p>
  
  <pre><code>describe('MyComponent', () =&gt; {
    let component: MyComponent;
    let fixture: ComponentFixture&lt;MyComponent&gt;;
    let myService: MyService;
  
    beforeEach(async (() =&gt; {
       TestBed.configureTestingModule(
     ).compileComponents();
  
     myService = TestBed.inject(MyService);
    }
  
    beforeEach(() =&gt; {
      fixture = TestBed.createComponent(MyComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
  
      spyOn(myService, 'saveOject').and.returnValue(new Promise(resolve =&gt; resolve()));
    });
  
    it('should call closeDialog method when save form is successful', () =&gt; {
       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
    });
  
  }
  </code></pre>
  
  <p>Can somebody help me ? 
  Sincerely</p>