在Jest中嵌套模拟函数

时间:2018-07-11 00:33:09

标签: javascript unit-testing testing mocking jestjs

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

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

function Orange(arg1, arg2){
   return (arg1 + arg2);
}

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

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

这是一个非常简单的示例,但是知道这一点绝对可以帮助我理解项目的下一步。希望很快能收到社区的来信!

1 个答案:

答案 0 :(得分:0)

这是解决方案:

enum childSumNames { child_incoming_costs = "isv_child_incoming_costs", child_est_revenue = "isv_child_est_revenue", child_margin = "isv_child_margin", } /** Only field names from childSumNames enum are allowed */ interface IChildSumFieldMapper { [key in childSumNames]: string // something like this (but it is incorrect syntax)... /* instead of this: * [childSumNames.child_incoming_costs]: string, * [childSumNames.child_est_revenue]: string, * [childSumNames.child_margin]: string, */ } // The example of IChildSumFieldMapper instance const item: IChildSumFieldMapper = { [childSumNames.child_incoming_costs]: "isv_incomingcost", [childSumNames.child_est_revenue]: "isv_estimatedrevenue", [childSumNames.child_margin]: "isv_margin", }

Apple.js

function Apple() { return Orange(1, 2); } function Orange(arg1, arg2) { return arg1 + arg2; } exports.Apple = Apple; exports.Orange = exports.Orange;

Apple.spec.js

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

const functions = require('./Apple.js');

describe('Apple', () => {
  it('Should run Apple', () => {
    functions.Orange = jest.fn().mockImplementation(() => {
      return 3;
    });
    expect(functions.Apple()).toEqual(3);
  });
});

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