angular - 如何使用 jest 框架模拟异步函数?

标签 angular reactjs typescript jestjs

我试图模拟调用服务和进程的异步函数,并解决异步函数的 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/

相关文章:

javascript - 带有 ConfirmDialog 的 PrimeNg TabView

css - 如何使外部自定义 css (style.css) 与 React 组件一起工作?

javascript - :host background color not set, 但是字体变大了?

html - ionic 以 MM 、 DD 、 YYYY 等格式显示当前时间

node.js - 使用代理时,运算符的 Rxjs 不发出值

javascript - 在操作之前检查 Javascript/Typescript 中嵌套的 JSON 以查看 Data 是否为 null

javascript - 同时使用 Angular 1 和 Angular 2

angular - 如何构造一个 Angular 库以具有多个导入路径(如 @angular/material),这样做有什么好处?

javascript - 难以遍历数组对象并从 Redux Store 中生成 JSX 中的动态 React 元素

html - Material-UI 中的 notched 属性应该做什么