lundi 2 décembre 2019

How do I resolve the outer promise inside a mocked function with Jest?

Here is my basic setup I'm trying to test.

First, Method I'm testing:

Thing.prototype.getStuff = function(){
   return new Promise((resolve, reject) => {
     // Bunch of business logic...
     this.getOtherStuff().then((data) => {
        // Perform business logic with data. I want to test that certain things get called depending on the response. 

        this._performLogic();

        // Now resolve outer promise here with new data
        resolve({newdata: goodstuff});
        // Or depending on the logic, reject
     })
   });
}

In my test for getStuff, I am mocking the response for getOtherStuff. I'm doing that like so:

Thing.prototype.getOtherStuff.mockImplementationOnce(()=> Promise.resolve({data: 'value'}));

So my whole test looks like this:

test('Here is my test name', async () => {
Thing.prototype.getOtherStuff.mockImplementationOnce(()=> Promise.resolve({data: 'value'}));

let instance = new Thing();

await instance.getStuff();

// We never get to this test because the test timeouts
expect(Thing.prototype._performLogic).toHaveBeenCalled()
});

So my test always timeout because I'm never resolving the outer promise in getStuff. I get this error:

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

How can I resolve this outer Promise while also mocking the inner async call getOtherStuff?

Aucun commentaire:

Enregistrer un commentaire