茉莉花测试通过调用spyOn模拟函数

时间:2019-01-24 00:38:12

标签: jasmine

我在茉莉花测试中还很新。

让我说我有这个sample.js文件:

(function() {

    function myFunction() {

        do some thing and then make a call to MyOtherFunciton
    }

    myOtherFunciton(p1, p2, p3) {
        //do some stuff in here 
    }
    module.exports = {
      myOtherFunciton,
      myFunction
    }
})();

现在我进行了茉莉花测试

   const mySampleFile = require(./sample.js);

   spyOn(mySampleFile, "myOtherFunciton").and.callFack(()=>{
   });
   mySampleFile.myFunction();
   expect(mySampleFile.myOtherFunciton).toHaveBeenCalled();

我遇到的问题是它调用了真正的myOtherFunciton函数,而不是模拟的函数。为什么会这样?

1 个答案:

答案 0 :(得分:1)

这是您遇到的功能范围问题。您发现,从myOtherFunciton()内部调用的函数myFunction()mySampleFile.myOtherFunciton()不同。要解决此问题,您需要对原始代码进行一些重构(测试暴露这些东西时您不喜欢它吗?)。我在下面添加了一些console.logs,目的是为了清楚测试过程中执行上下文的去向。

建议的重构:

(function() {

    exports.myFunction = function() {
        // do some thing and then make a call to MyOtherFunciton
        console.log('inside myFunction');
        exports.myOtherFunciton('a', 'b', 'c'); // scoped to exports, now can be mocked
        // myOtherFunciton('a', 'b', 'c'); // <-- don't call it like this: scoped within IIFE
    }

    exports.myOtherFunciton = function(p1, p2, p3) {
        console.log('inside original myOtherFunciton');
        //do some stuff in here 
    }
    // module.exports = {
    //   myOtherFunciton,
    //   myFunction
    // }
})();

这是一个有效的StackBlitz,显示现在通过了测试。单击Jasmine测试窗口下方的“控制台”以查看输出。

我希望这会有所帮助。

相关问题