简体   繁体   中英

Typescript - Jest: Mock indirect function call

Let's say I have two files, that contain the following functions:

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; }

To summarize it's like this:

在此处输入图像描述

In my test file file-test.ts , I now want to test fnA but I want to mock fnB2 to not return 5 but to return 42 . How can I achieve that?

I think I found a possible solution:

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);
}

But in order to make this work, I had to change file-b.ts . I had to add a exports. in front of the function call:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM