Jest 中的嵌套模拟函数

Sea*_*ean 5 javascript testing unit-testing mocking jestjs

我目前正在尝试测试模拟我的一些笑话功能。我遇到的问题之一是尝试模拟在另一个函数内部调用的函数。这是我正在尝试做的事情的高级示例:

//Apple.js
function Apple(){
   return Orange(1, 2);
}

function Orange(arg1, arg2){
   return (arg1 + arg2);
}
Run Code Online (Sandbox Code Playgroud)

我想测试 Apple 功能而不实际调用 Orange。在 .spec.js 文件中模拟我的橙色函数以使类似的事情发生的代码是什么?我当时在想类似以下的事情,但我对此表示怀疑:

//Apple.spec.js
import Apple from "Apple.js";
it("Should run Apple", () => {
   global.Orange = jest.fn().mockImplementation(() => {return 3});
   expect(Apple()).toEqual(3);
});
Run Code Online (Sandbox Code Playgroud)

这是一个非常简单的例子,但了解这一点肯定会帮助我理解项目的下一步。我希望尽快收到社区的来信!

sli*_*wp2 2

这是解决方案:

\n\n

Apple.js:

\n\n
function Apple() {\n  return Orange(1, 2);\n}\n\nfunction Orange(arg1, arg2) {\n  return arg1 + arg2;\n}\n\nexports.Apple = Apple;\nexports.Orange = exports.Orange;\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

Apple.spec.js:

\n\n
const functions = require(\'./Apple.js\');\n\ndescribe(\'Apple\', () => {\n  it(\'Should run Apple\', () => {\n    functions.Orange = jest.fn().mockImplementation(() => {\n      return 3;\n    });\n    expect(functions.Apple()).toEqual(3);\n  });\n});\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
PASS  src/stackoverflow/51275648/Apple.spec.js\n  Apple\n    \xe2\x9c\x93 Should run Apple (4ms)\n\n----------|----------|----------|----------|----------|-------------------|\nFile      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |\n----------|----------|----------|----------|----------|-------------------|\nAll files |      100 |      100 |      100 |      100 |                   |\n Apple.js |      100 |      100 |      100 |      100 |                   |\n----------|----------|----------|----------|----------|-------------------|\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        4.312s\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是完成的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/51275648

\n