简体   繁体   中英

path resolve method mocking with Jest

I want to mock the resolve method that is part of the "path" module. I am using it in a method and i want to mock the response of path.resolve(filepath) so i can write some unitTests based on that.

You can jest.spyOn(object, methodName) to mock path.resolve method.

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

unit test results with 100% coverage:

 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

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