首页 > 解决方案 > 茉莉花测试通过调用 spyOn 模拟函数

问题描述

我在茉莉花测试中很新。

假设我有这个 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 函数,而不是模拟的函数。这是为什么 ?

标签: jasmine

解决方案


这是您遇到的功能范围问题。正如您所发现的,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 测试窗口下方的“控制台”以查看输出。

我希望这有帮助。


推荐阅读