如何使用 jest 获取模拟实用函数

5 reactjs jestjs

我有一个从实用程序调用函数的反应模块。我\xe2\x80\x99m 测试组件并模拟实用函数,但不知何故我\xe2\x80\x99m 没有获得它的行覆盖率。我嘲笑实用程序函数以得到错误的测试,但它\xe2\x80\x99s仍然通过,让我想知道\xe2\x80\x99s有什么可疑的事情发生。

\n\n

关于如何模拟实用函数的任何提示或指南?

\n\n
//Utils.js\nexport const add = () => {\n    return x;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

add函数在App模块中使用。我想测试应用程序,但模拟没有返回我期望它返回的内容。

\n\n
//Mocking as below\njest.mock('../utils', () => ({\n    ...jest.requireActual('../utils'),\n    add:() => 4\n}));\n
Run Code Online (Sandbox Code Playgroud)\n

sli*_*wp2 9

您可以使用jest.spyOn它来制作方法的存根utils.add

\n\n

例如

\n\n

App.js:

\n\n
import * as utils from \'./Utils\';\n\nexport function bootstrap() {\n  return utils.add();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

Utils.js:

\n\n
export const add = () => {\n  const x = 1;\n  return x;\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

App.test.js:

\n\n
import { bootstrap } from \'./App\';\nimport * as utils from \'./Utils\';\n\ndescribe(\'bootstrap\', () => {\n  it(\'should mock utils.add method correctly\', () => {\n    const addStub = jest.spyOn(utils, \'add\').mockReturnValueOnce(2);\n    const actual = bootstrap();\n    expect(actual).toBe(2);\n    expect(addStub).toBeCalledTimes(1);\n    addStub.mockRestore();\n  });\n\n  it(\'should pass\', () => {\n    expect(utils.add()).toBe(1);\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
 PASS  src/stackoverflow/59208419/App.test.js (7.993s)\n  bootstrap\n    \xe2\x9c\x93 should mock utils.add method correctly (5ms)\n    \xe2\x9c\x93 should pass (1ms)\n\n----------|----------|----------|----------|----------|-------------------|\nFile      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |\n----------|----------|----------|----------|----------|-------------------|\nAll files |      100 |      100 |      100 |      100 |                   |\n App.js   |      100 |      100 |      100 |      100 |                   |\n Utils.js |      100 |      100 |      100 |      100 |                   |\n----------|----------|----------|----------|----------|-------------------|\nTest Suites: 1 passed, 1 total\nTests:       2 passed, 2 total\nSnapshots:   0 total\nTime:        9.072s\n
Run Code Online (Sandbox Code Playgroud)\n\n

源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59208419

\n