DEV Community

Dennis Zhang
Dennis Zhang

Posted on

jest.mock()模拟某个模块

假设 example.js 现在包含多个导出:

// example.js
export default function fetchData() {
  return 'real data';
}

export function otherFunction() {
  return 'something else';
}

export function otherFunc() {
  return 'something else';
}
Enter fullscreen mode Exit fullscreen mode

模拟默认导出的 fetchData 函数,同时保留 otherFunction:

import fetchData, { otherFunction } from './example';

jest.setTimeout(30000) // 设置整体测试超时时间
jest.resetModules();  // 重置模块缓存

jest.mock('./example', () => {
  const actualModule = jest.requireActual('./example');
  return {
    __esModule: true,// 表明这是一个 ES 模块
    ...actualModule, // 保留其他导出
    otherFunction:jest.fn().mockImplementtation(()=>{
      return {  
        ss:xxx
       }
   })
    default: jest.fn(() => 'mocked data'), // 模拟默认导出
  };
});

test('should return mocked data', () => {
  expect(fetchData()).toBe('mocked data');
});

test('otherFunction should return real data', () => {
  expect(otherFunction()).toBe('something else');
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)