首页 > 解决方案 > 如何测试返回承诺的链式方法?

问题描述

我有一个返回已解决承诺的方法。我遇到的问题是如何测试该承诺的解决方案。

基本上发生的事情是,我通过其他功能链更新我的文档,当该文档被保存时,我想显示一个警报。现在我无法测试我的分辨率。截至目前,警报从未被调用。

如果可能的话,我想使用本机承诺而不是其他库。我将如何测试事物以确保调用我的警报方法。

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}`})

    })
  }

// 我的测试

 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(); 
    })

});

标签: angularjasmineangular-test

解决方案


推荐阅读