mercredi 25 novembre 2015

Testing an immediately invoked javascript file/function

I have a file which contains some code wrapped in a function a bit like this:

(function(W) {
  var Me = {
    init: function() { }
  };
  Me.init();
  globals.Me = Me;
})(self || window);

The code is aimed to be browser based and needs to be standalone/generic (i.e. not part of any framework/loader - a bit like a custom GA analytics file).

I need to pass window and some of its params such as location.search and these are modified for each test. I have chosen to add the self || window so that I could mock the window object in each test:

global.self = { document: {}, location: {} }

The problem that I am having is that with the ways that I am running my tests the browser code only seems to be invoked once for the entire test run and I want to run init() each time:

 it('run test', function() {
  // Define the mock "window" object
  global.self = {
    document: {
      referrer: 'http://google.com'
    }
  };
  // Load the file
  require('../../lib/thebrowserfile');
  Me.someFunc();      
});

I realize that part of my issue is that I am not loading the browser file as a browser would so I think I need to perhaps refactor that code to be more flexible. Suggestions for a better design pattern? Note that this is a unit test so I am not looking for e2e solutions.

Aucun commentaire:

Enregistrer un commentaire