Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock async function using jest framework?

i tried to mock the async function that is making call to service and process and resolve promise for the async function. so in below code its not mocking for some reason , any idea what i have implemented incorrect ?

Any example how to mock async function with below code will be highly appreciated.

main.ts

export async function getMemberInfoCache(tokenID: string): Promise < IInfoObj[] > {
    if (!tokenID) {
        throw new Error("tokenID needed for getMemberInfoCache");
    }
    const cacheObj: IGetCacheRequest = {
        key: tokenID,
        cachetype: "memberInfoCache"
    };
    const memberInfo = await CacheController.getInstance().getDetailsWrapper(cacheObj);

    const specialtyMemberObjs: any = [];
    const cacheArray: IspecialtyMemberInfo = memberInfo.cacheobject.specialtyMemberInfo;
        memberObj.lastName = member.memberInfo.lastName;
        memberObj.dateOfBirth = member.memberInfo.dateOfBirth;

        specialtyMemberObjs.push(memberObj);
    });

    return specialtyMemberObjs;
}

main.spec.ts

import {
    getMemberInfoCache
} from "./main.ts"
jest.mock(. / main.ts)

describe("Testing afterSpread passMakeResponse", () => {
    let callCacheFunction;
    beforeEach(async () => {
        callCacheFunction = await getMemberInfoCache.mockImplementation(() => {
            Promise.resolve([{
                key: value
            }]);
        });

    });
    it('should call afterSpread', function() {
        expect(callCacheFunction).toHaveBeenCalled();
    });

});
like image 335
hussain Avatar asked Dec 17 '22 20:12

hussain


1 Answers

Aysnc functions are just functions that return a promise. You simply need to mock the function as you have done using jest.mock and then provide a mock return value. Here is one way to write a test against the getMemberInfoCache function.

describe("Testing afterSpread passMakeResponse", async () => {
    it('should call afterSpread', function() {
      getMemberInfoCache.mockReturnValue(Promise.resolve([{
        key: value
      }]);

      await getMemberInfoCache();

      expect(callCacheFunction).toHaveBeenCalled();
    });

});

One thing to note is that jest.mock will stub getMemberInfoCache for you so whenever you call getMemberInfoCache in your test file it will be calling the stubbed version.

like image 147
Teddy Sterne Avatar answered Dec 28 '22 09:12

Teddy Sterne