使用 Jest 模拟路径解析方法

Gan*_*esh 0 javascript unit-testing node.js typescript jestjs

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

sli*_*wp2 5

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

\n\n

例如\n main.ts

\n\n
import path from \'path\';\n\nexport function main(filepath) {\n  return path.resolve(filepath);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

main.test.ts:

\n\n
import { main } from \'./main\';\nimport path from \'path\';\n\ndescribe(\'61419093\', () => {\n  it(\'should pass\', () => {\n    const resolveSpy = jest.spyOn(path, \'resolve\').mockReturnValueOnce(\'/fakepath\');\n    const actual = main(\'/root/avatar.jpg\');\n    expect(actual).toBe(\'/fakepath\');\n    expect(resolveSpy).toBeCalledWith(\'/root/avatar.jpg\');\n    resolveSpy.mockRestore();\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
 PASS  stackoverflow/61419093/main.test.ts (12.631s)\n  61419093\n    \xe2\x9c\x93 should pass (4ms)\n\n----------|---------|----------|---------|---------|-------------------\nFile      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n----------|---------|----------|---------|---------|-------------------\nAll files |     100 |      100 |     100 |     100 |                   \n main.ts  |     100 |      100 |     100 |     100 |                   \n----------|---------|----------|---------|---------|-------------------\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        14.426s\n
Run Code Online (Sandbox Code Playgroud)\n