简体   繁体   中英

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

});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM