【问题标题】:How can I mock path with path.win32 in jest?我怎样才能开玩笑地用 path.win32 模拟路径?
【发布时间】:2022-12-09 11:47:53
【问题描述】:

我希望我的测试套件像在 Windows 平台上一样工作。不幸的是,很多依赖项使用 path 模块。我想用 path.win32 实现来模拟它。但是,这种方法不起作用:

const winPath = require("path").win32;
jest.mock("path", () => winPath);

ReferenceError:初始化前无法访问“winPath”

这样做的正确方法是什么?

【问题讨论】:

    标签: node.js jestjs mocking


    【解决方案1】:

    jest.mock() 应该可以。下面的示例显示了如何模拟 win32.normalize() 方法。

    const winPath = require("path").win32;
    
    jest.mock('path', () => {
      return {
        ...(jest.requireActual('path') as typeof import('path')),
        win32: {
          normalize: jest.fn(),
        }
      }
    })
    
    describe('74717157', () => {
      test('should pass', () => {
        winPath.normalize.mockImplementation(() => 'override the original implementation')
        expect(jest.isMockFunction(winPath.normalize)).toBeTruthy();
        expect(winPath.normalize()).toBe('override the original implementation')
      })
    })
    

    测试结果:

     PASS  stackoverflow/74717157/index.test.ts (10.557 s)
      74717157
        ✓ should pass (1 ms)
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        14.116 s
    

    【讨论】:

      猜你喜欢
      • 2019-07-09
      • 1970-01-01
      • 2017-11-23
      • 2020-09-08
      • 2015-10-07
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多