我试图模拟调用服务和进程的异步函数,并解决异步函数的 promise 。所以在下面的代码中它不是出于某种原因 mock ,知道我实现了什么不正确吗?
任何如何使用以下代码模拟异步函数的示例都将受到高度赞赏。
主文件
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;
}
主要规范
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 函数只是返回 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
stub getMemberInfoCache
为您服务,无论您何时调用 getMemberInfoCache
在您的测试文件中,它将调用 stub 版本。
关于angular - 如何使用 jest 框架模拟异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52703859/