首页 > 解决方案 > Jest mock 没有从另一个模块 Typescript 导出函数

问题描述

我希望能够模拟未导出但在我要测试的函数中使用的函数。这是小代码示例。

文件.ts

const hello  = () => {
    console.log('hello');
}

export const say = () =>{
    hello  ()
    return 10;
}

文件.test.ts

  import {say } from 'file'; 

  describe("Test ", () => {
        it("test", async () => {
            // how to mock hello before that ? 
            say();
            
         
        })
    })

标签: typescriptjestjs

解决方案


Jest 能够模拟 ES 模块(整个 ts/js 文件),但使用您当前的实现是不可能的。

我的建议是提取function hello到另一个名为的文件hello.ts中并导入以供function say使用。然后 jest 可以模拟hello.ts

示例代码:

// hello.ts
export const hello  = () => {
  console.log('hello');
}
// say.ts
import { hello } from "./hello";

export const say = () =>{
  hello();
  return 10;
}
// say.test.ts
import { say } from './say';

jest.mock('./hello', () => {
  return {
    hello: jest.fn().mockImplementation(() => {
      console.log('mock hello');
    })
  };
});

describe('Test ', () => {
  it('test', async () => {
    // how to mock hello before that ?
    say();
  });
});

输出:

在此处输入图像描述


推荐阅读