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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With