我有一个从实用程序调用函数的反应模块。我\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}\nRun Code Online (Sandbox Code Playgroud)\n\nadd函数在App模块中使用。我想测试应用程序,但模拟没有返回我期望它返回的内容。
//Mocking as below\njest.mock('../utils', () => ({\n ...jest.requireActual('../utils'),\n add:() => 4\n}));\nRun Code Online (Sandbox Code Playgroud)\n
您可以使用jest.spyOn它来制作方法的存根utils.add。
例如
\n\nApp.js:
import * as utils from \'./Utils\';\n\nexport function bootstrap() {\n return utils.add();\n}\nRun Code Online (Sandbox Code Playgroud)\n\nUtils.js:
export const add = () => {\n const x = 1;\n return x;\n};\nRun Code Online (Sandbox Code Playgroud)\n\nApp.test.js:
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});\nRun Code Online (Sandbox Code Playgroud)\n\n100%覆盖率的单元测试结果:
\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\nRun Code Online (Sandbox Code Playgroud)\n\n源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59208419
\n| 归档时间: |
|
| 查看次数: |
13114 次 |
| 最近记录: |