我试图模拟异步函数,该函数正在调用服务和流程并解决了对异步函数的承诺。因此,在下面的代码中由于某种原因它没有被嘲笑,我知道我实现了什么错误吗?
任何使用以下代码模拟异步功能的示例都将受到高度赞赏。
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();
});
});
答案 0 :(得分:1)
Aysnc函数只是返回promise的函数。您只需要像使用jest.mock
一样模拟函数,然后提供模拟返回值。这是针对getMemberInfoCache
函数编写测试的一种方法。
describe("Testing afterSpread passMakeResponse", async () => {
it('should call afterSpread', function() {
getMemberInfoCache.mockReturnValue(Promise.resolve([{
key: value
}]);
await getMemberInfoCache();
expect(callCacheFunction).toHaveBeenCalled();
});
});
要注意的一件事是jest.mock
将为您存根getMemberInfoCache
,因此,每当您在测试文件中调用getMemberInfoCache
时,它将调用存根版本。