lundi 2 décembre 2019

How do I call a resolve in the callback of a mocked function?

Here is the function I am trying to test:

//index.js
import ThirdParty from 'third-party';

Main(){}

Main.prototype.getStuff = function(){
   return new Promise((resolve, reject) => {
      this.getOtherStuff().then((data) => {
         // Business logic...
         const tpinstance = new ThirdParty();

         tpinstance.createThing().nestedFunction(null, () => {
             // This is where I'm resolving the outer function
             resolve({newdata: goodstuff});
         });
      });
   }
}

Main.prototype.getOtherStuff = function(){
   return new Promise((resolve, reject) => {
     resolve();
   })
}

I am failing to resolve the the promise from the outer most function so I'm getting this error:

Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:

My Test

//index.spec.js
import ThirdParty from 'third-party';

jest.mock('third-party');

describe('Main', () => {
   describe('#getStuff', () => {
      test('Want this to pass', async () => {

         jest
           .spyOn(Main.prototype, "getOtherStuff")
           .mockImplementationOnce(() => Promise.resolve({ data: "value" }));

         const mockedThing = {
            // This implementation seems wrong to me.
            nestedFunction: jest.fn().mockImplementation(() => Promise.resolve())
         }

         jest
           .spyOn(ThirdParty.prototype, "createThing")
           .mockImplementation(() => (mockedThing))

         let instance = new Main();
         await instance.getStuff();

         //assertions -> I never get here cause it timesout
         expect(Main.prototype.getOtherStuff).toHaveBeenCalled();
      });
   });
});

How can I mock out nestedFunction in a way where I'll be resolving the outer function in a callback I pass to nestedFunction?

Aucun commentaire:

Enregistrer un commentaire