有没有办法监视Promise构造函数?

时间:2019-10-02 11:33:41

标签: jasmine jestjs

我有这个功能

public pick(config?: FilePickerConfig): Promise<FilePickerResult> {
    return new Promise<FilePickerResult>(resolve => {
      this.pickWithCallbacks(resolve, resolve, config);
    });
  }

我想测试对this.pickWithCallbacks的调用是否具有函数的resolve参数作为第一个和第二个参数。

有没有办法用开玩笑或茉莉花来做到这一点?我曾尝试监视window, 'Promise',但无法正常工作。

编辑:它不是Spying on a constructor using Jasmine的重复版本,因为这是我尝试过的并且没有起作用。

我已经尝试过了:

      const dummyResolve = () => { };
      const promiseSpy = spyOn(window, 'Promise').and.callFake((dummyResolve)=>{});
      const pickWithCallbacksSpy = spyOn(sut, 'pickWithCallbacks');
      sut.pick();

      expect(pickWithCallbacksSpy).toHaveBeenCalledWith(dummyResolve, dummyResolve, undefined);

1 个答案:

答案 0 :(得分:1)

所以最后我只剩下Promise做他的事,我捕获了解析回调

    test('on success should call pickWithCallbacks with the resolve function of a promise', (done) => {
      const cordovaExecSpy = spyOn(sut, 'pickWithCallbacks');
      const dummyReturn = {};
      sut.pick().then(obtained => {
        expect(obtained).toBe(dummyReturn);
        done();
      });

      const capturedOnSucess = cordovaExecSpy.calls.mostRecent().args[0];
      capturedOnSucess(dummyReturn);
    });

    test('on Error should call pickWithCallbacks with the resolve function of a promise', (done) => {
      const cordovaExecSpy = spyOn(sut, 'pickWithCallbacks');
      const dummyReturn = {};
      sut.pick().then(obtained => {
        expect(obtained).toBe(dummyReturn);
        done();
      });

      const capturedOnError = cordovaExecSpy.calls.mostRecent().args[1];
      capturedOnError(dummyReturn);
    });