2016-11-28 81 views
1

我想用茉莉花來spyOn其中出口直接的方法的模塊:如何spyOn的NodeJS模塊單茉莉

Mymodule中

module.exports = (arg, arg) => { 
    //do something... 
    callAMethod(); 
    //return 
} 

茉莉花

spyOn(myModule); 
// since I don't have any method to use spyOn(myModule, <method>) 

我發現我可以使用這個:

//describe.. 
    var myModule = require('./myModule'); 

     it... 
     myModule = jasmine.createSpy().and.callFake(function() { 
      return false; 
     }); // <-this should work 

     functionBeingTested(..args); 

     expect(myModule).toHaveBeenCalled(); /*I get false, even if 
               it is actually called 
               in the functionBeingTested*/ 

我發現的另一個解決方案是spyOn myModule.prototype或設置jasmine.createSpy().and.returnValue(false)但我都沒有成功。

我如何使用spyOn像我上面所說的?

回答

0
  • 我創建了一個簡單的snippet其模仿要求JS 功能加載庫並調用該方法。

  • 我列出每次三名間諜用不同的場景,說明如何 窺探

注:

  • 我本身不是使用require.js但模仿其功能 然而
  • 因爲require.js exportsmodule.exports,我們有沒有 控制require調用的功能,因此我們可能 不能在該方法上安裝間諜。
  • 請按照每個案例進行說明。

希望這有助於!

var callAMethod = function() { 
     return "Hello"; 
    } 
    var myModule = {}; 
    myModule.exports = function(name, title) { 
    return callAMethod() + " " + title + "." + name; 
    } 

    // Note that this require mimics the actual require.js require methodology, bascially returns the instantiated version of the library to be used. 
    var require = function() { 
     return myModule.exports; 
    } 

    // some function that uses the require library to load the js and then does something with it. 
    var testFunc = function() { 
     var myMod = require('abc'); 
     return myMod("Bruce", "Mr"); 
    } 

    describe('test mymodule', function() { 
     // This test fails because though you are mocking the instance here and not the actual call. 
     it('test that fails', function() { 
     var myModuleTest = require('abc'); 
     myModuleTest = jasmine.createSpy().and.callFake(function() { 
      return false; 
     }); 
     var result = testFunc(); 
     console.log(result); 
     expect(result).toBe(false); 
     }); 
     // this test passes since we have hijacked the require attribute itself and then routed its call to return the Boolean true which means that myModule now return the true statement 
     it('test that passes', function() { 
     require = jasmine.createSpy().and.callFake(function() { 
      return function() { 
      return true; 
      }; 
     }); 
     var result = testFunc(); 
     console.log(result); 
     expect(result).toBe(true); 
     }); 

     //callAMethod method call from module.exports may not tested since its the require js that does this call and you have no hook into it, however you can directly test the method like this 
     it('test callAMethod', function() { 
     console.log(myModule.exports("Bruce", "Mr")); 
     spyOn(myModule, 'exports').and.returnValue("Hello Mr.Wayne!"); 
     var testVal = myModule.exports("Bruce", "Mr"); 
     expect(testVal).toEqual("Hello Mr.Wayne!"); 
     }) 


    });