0

I have this function

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

I want to test if the call to this.pickWithCallbacks has as first and second parameter the resolve parameter of the function.

Is there a way to do this in jest or jasmine? I have tried to spy on window, 'Promise' but it does not work.

Edit: It is not a depulicate of Spying on a constructor using Jasmine because that is what I have tried and did not work.

I have tried this:

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

      expect(pickWithCallbacksSpy).toHaveBeenCalledWith(dummyResolve, dummyResolve, undefined);
skyboyer
  • 22,209
  • 7
  • 57
  • 64
distante
  • 6,438
  • 6
  • 48
  • 90
  • Possible duplicate of [Spying on a constructor using Jasmine](https://stackoverflow.com/questions/9347631/spying-on-a-constructor-using-jasmine) – Igor Oct 02 '19 at 11:38
  • Can you add the code ypu have tried? – Jonathan Larouche Oct 02 '19 at 11:38
  • @JonathanLarouche I will see if I have it in my ctrl-z history. I am trying many things. – distante Oct 02 '19 at 11:39
  • Can you just spy the function `pickWithCallbacks` with jest.fn()? Eg: Mock the method with: `obj.pickWithCallbacks = jest.fn();` then call the pick method `obj.pick(config);` and after verify the outcome `expect(obj.pickWithCallbacks).toHaveBeenCalledWith(valueForResolve, valueForResolve, valueForConfig);` – Jonathan Larouche Oct 02 '19 at 11:49
  • @JonathanLarouche I have tried something like that. I have updated my question – distante Oct 02 '19 at 12:01

1 Answers1

1

So finally I just left the Promise do his thing and I captured the resolve callback

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

distante
  • 6,438
  • 6
  • 48
  • 90