【问题标题】:Typescript - Jest: Mock indirect function callTypescript - Jest:模拟间接函数调用
【发布时间】:2022-07-22 15:54:05
【问题描述】:

假设我有两个文件,其中包含以下函数:

file-a.ts:

import { fnB1 } from "./file-b";

export function fnA(): number { return fnB1(); }

file-b.ts:

export function fnB1(): number { return fnB2(); }
export function fnB2(): number { return 5; }

总结如下:

在我的测试文件file-test.ts 中,我现在想测试fnA,但我想模拟fnB2 不返回5,而是返回42。我怎样才能做到这一点?

【问题讨论】:

    标签: typescript jestjs ts-jest


    【解决方案1】:

    我想我找到了一个可能的解决方案:

    file-test.ts:

    import { fnA } from "./file-a";
    import * as FileB from "./file-b";
    
    it('should work', () => {
       jest.spyOn(FileB, 'fnB2').mockReturnValue(42);
    
       expect(fnA()).toBe(42);
    }
    

    但为了完成这项工作,我不得不更改 file-b.ts。我必须在函数调用前添加一个exports.:

    export fnB1() { return exports.fnB2(); }
    export fnB2() { return 5; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 2023-03-04
      • 2022-08-23
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 2020-02-26
      相关资源
      最近更新 更多