2017-10-20 147 views
0

我想添加一個測試,它將覆蓋CommonJS文件module1.js中的返回語句,請參閱附加圖像。karma-jasmine - 如何測試返回對象

這裏就是我目前正試圖:

describe("Module 1 ",() => { 
    let mod, testMod = null; 

    beforeEach(() => { 
     mod = { 
      module1: require('../src/app/js/module1/module1') 
     }; 

     spyOn(mod, 'module1'); 
     testMod = mod.module1(); 
     console.log(testMod); 
     console.log(mod.module1); 
    }); 
    it('is executed',() => { 
     expect(mod.module1).toHaveBeenCalled(); 
    }); 
}); 

模塊1文件:

/** 
* Represents module1. 
* @module module1 
*/ 

function module1() { 
    let x = 13; 

    return { 
     getUserAgent: getUserAgent 
    }; 

    /** 
    * Return the userAgent of the browser. 
    * @func getUserAgent 
    */ 
    function getUserAgent() { 
     return window.navigator.userAgent 
    } 
} 

module.exports = module1; 

日誌輸出:

LOG: undefined 
LOG: function() { ... } 

更新:當我登錄mod.module.toString,控制檯日誌:

function() { return fn.apply(this, arguments); }

爲什麼我的模塊不在那裏?

我在這裏嘗試正確的方法嗎?爲什麼不mod.module1();工作?

Istanbul coverage Report

回答

0

當您在茉莉花設置對象方法間諜原有功能不被調用。 因此,在你的例子中,mod.module1() doesn調用實際模塊函數,但只有間諜包裝函數 - 實際函數根本不被調用。
如果你想原始函數被調用,你應該使用and.callThrough

spyOn(mod, 'module1').and.callThrough(); 
相關問題