【问题标题】:Angular 5 - Angular firebase - Testing - mocking getDownloadURL methodAngular 5 - Angular firebase - 测试 - 模拟 getDownloadURL 方法
【发布时间】:2018-04-07 16:50:55
【问题描述】:

我在模拟控制台每次显示的 getDownLoadURL 方法时遇到了困难: TownhallPictureService 应通过有效输入返回市政厅级别 FAILED TypeError: this.ref.getDownloadURL is not a function

我的服务看起来像:

@Injectable()
export class TownhallPictureService {

  public ref;

  constructor(private storage: AngularFireStorage) {
  }

  getTownHallPicture(townhall: number): Observable<string | null> {
    switch (townhall) {
      case 1:
        this.ref = this.storage.ref(TownhallImgSrc.TOWNHALL_ONE);
        break;
        ...
        break;
      case 11:
        this.ref = this.storage.ref(TownhallImgSrc.TOWNHALL_ELEVEN);
        break;
      default:
        return Observable.of(undefined);
    }
    return this.ref.getDownloadURL();
  }
}

还有茉莉花规格文件:

    describe('TownhallPictureService', () => {
  let spy;
  const angularFireMock = {
    ref(){
      function getDownloadURL() {}
    },
  };
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [TownhallPictureService,
        {provide: AngularFireStorage, useValue: angularFireMock},
        ]
    });
    spy = TestBed.get(AngularFireStorage);
  });

  it('should be return townhall level by valid input', inject(
    [TownhallPictureService], (service: TownhallPictureService) => {
      const expectedTownhall: number = 9;
      const expectedPicture: string = TownhallImgSrc.TOWNHALL_NINE;

      spyOn(spy, 'ref').and.returnValue(Observable.of(TownhallImgSrc.TOWNHALL_NINE));

      service.getTownHallPicture(expectedTownhall).subscribe(result => {
        expect(result).toBe(expectedPicture);
      });
    }));

有谁知道如何正确模拟此方法?这里的问题是:getDownloadURL 是来自不同类的方法,所以我需要某种嵌套的模拟 obj。

【问题讨论】:

    标签: angular unit-testing firebase testing karma-jasmine


    【解决方案1】:

    对于使用 AngularFirebaseStorage 并希望围绕此服务构建单元测试的人,这是模拟 ref() 和 getDownloadURL() 的方式: 创建一个 FakeClass:

    export class FirebaseMock {
    
      public ref(path: string) {
          return {
            getDownloadURL() {
              return Observable.of(path)
            }
          }
      }
    }
    

    并将其注入到需要测试的类的构造函数中:

    let mock: any;
      let service: TownhallPictureService;
    
      beforeEach(() => {
        mock = new FirebaseMock();
        service = new TownhallPictureService(mock);
      });
    

    【讨论】:

    • 有没有办法使用相同的答案,但使用 TestBed.inject ?
    猜你喜欢
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多