2

I have a method that returns a resolved promise. The issue I'm running into is how to test the resolution of that promise.

Essentially what happens is, I update my document via chain of other functions & when that document is saved, I want to show an alert. Right now I'm unable to test my resolution. As of now the alert never gets called.

I'd like to use native promises & not other libraries if possible. How would I test things so that I can ensure my alert method is called.

public update(doc):Promise<any> {
    return collection.doc(doc.id).update(doc).then(res=>{
      console.log('This is never run')
      this.alert.insert({type:"success", message:"Updated"})
    })
    .catch(err=>{
      console.log('Neither is this')

      this.alert.insert({type:"error", message:`Error - Updating ${err}`})

    })
  }

// my test

 beforeEach(() => {

    afSpy = jasmine.createSpyObj('AngularFirestore', ['collection', 
    'valueChanges', 'snapshotChanges', 'ref', 'doc','add','update', 
    'then', 'catch', 'finally', 'firestore', 'batch']);
    afSpy.collection.and.returnValue(afSpy);
    afSpy.valueChanges.and.returnValue(afSpy);
    afSpy.snapshotChanges.and.returnValue(afSpy); 
    afSpy.ref.and.returnValue(afSpy); 
    afSpy.doc.and.returnValue(afSpy); 
    afSpy.add.and.returnValue(afSpy); 
    afSpy.update.and.returnValue(afSpy); 
    afSpy.then.and.returnValue(Promise.resolve('hello world')); 
    afSpy.catch.and.returnValue(afSpy); 
    afSpy.finally.and.callThrough()
    afSpy.firestore.and.returnValue(afSpy); 
    afSpy.batch.and.returnValue(afSpy); 

    TestBed.configureTestingModule({
      providers:[
        { provide: AngularFirestore, useValue: afSpy },
      ],      
    })
fit('temporary test', (done) => {

    service.update(mockDoc).then(x=>{
      expect(updateSpy).toHaveBeenCalledWith(mockDoc); //this passes
      console.log(x)
      expect(alertServiceSpy.insert).toHaveBeenCalled() // this fails
      done(); 
    })

});
Justin Young
  • 2,393
  • 3
  • 36
  • 62
  • 1
    Possible duplicate of [How do I mock a service that returns promise in Angularjs Jasmine unit test?](https://stackoverflow.com/questions/23705051/how-do-i-mock-a-service-that-returns-promise-in-angularjs-jasmine-unit-test). I think you're on the right track. Look at the SO post I cited. Also, look here: https://medium.com/dailyjs/unit-testing-async-calls-and-promises-with-jasmine-a20a5d7f051e – paulsm4 Jan 04 '19 at 21:00

0 Answers0