【问题标题】:Is there a way to spy on a Promise constructor?有没有办法监视 Promise 构造函数?
【发布时间】:2019-10-02 20:30:19
【问题描述】:

我有这个功能

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

【问题讨论】:

  • 你能添加你尝试过的代码吗?
  • @JonathanLarouche 我会看看我的 ctrl-z 历史中是否有它。我正在尝试很多事情。
  • 你能用 jest.fn() 监视函数pickWithCallbacks 吗?例如:用obj.pickWithCallbacks = jest.fn(); 模拟方法,然后调用pick 方法obj.pick(config); 并在验证结果后expect(obj.pickWithCallbacks).toHaveBeenCalledWith(valueForResolve, valueForResolve, valueForConfig);
  • @JonathanLarouche 我尝试过类似的方法。我已经更新了我的问题

标签: jasmine jestjs


【解决方案1】:

所以最后我只是让 Promise 做他的事情,我捕获了 resolve 回调

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

【讨论】:

  • 很高兴你成功了,我更习惯用jest.fn() 编码而不是spyOn。感谢您分享您的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-11
  • 2021-11-11
  • 2011-07-28
  • 1970-01-01
  • 1970-01-01
  • 2011-10-08
相关资源
最近更新 更多