【问题标题】:path resolve method mocking with Jest用 Jest 模拟路径解析方法
【发布时间】:2020-08-08 15:49:42
【问题描述】:

我想模拟作为“路径”模块一部分的解析方法。 我在一个方法中使用它,我想模拟path.resolve(filepath) 的响应,所以我可以基于它编写一些单元测试。

【问题讨论】:

    标签: javascript node.js typescript unit-testing jestjs


    【解决方案1】:

    你可以jest.spyOn(object, methodName)模拟path.resolve方法。

    例如 main.ts:

    import path from 'path';
    
    export function main(filepath) {
      return path.resolve(filepath);
    }
    

    main.test.ts:

    import { main } from './main';
    import path from 'path';
    
    describe('61419093', () => {
      it('should pass', () => {
        const resolveSpy = jest.spyOn(path, 'resolve').mockReturnValueOnce('/fakepath');
        const actual = main('/root/avatar.jpg');
        expect(actual).toBe('/fakepath');
        expect(resolveSpy).toBeCalledWith('/root/avatar.jpg');
        resolveSpy.mockRestore();
      });
    });
    

    100% 覆盖率的单元测试结果:

     PASS  stackoverflow/61419093/main.test.ts (12.631s)
      61419093
        ✓ should pass (4ms)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |     100 |      100 |     100 |     100 |                   
     main.ts  |     100 |      100 |     100 |     100 |                   
    ----------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        14.426s
    

    【讨论】:

    • 谢谢!这就是我要找的东西!
    猜你喜欢
    • 2018-09-11
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 2021-04-11
    相关资源
    最近更新 更多