0

I had some Javascript code and I wanted to make it reusable and testable so I'm trying to make a library out of it. I've already made it in the form of a library but I'm not able to test the constructor using Jasmine.

My library code looks this way:

window.menu = (function(){

  function Menu(){
    this.addItem('sample');
  }

  Menu.prototype.addItem(string){
    console.log(string);
  }

  var menu = function(){
    return new Menu();
  }

return menu;
}());

Now using Jasmine, I wan't to write a test for testing not the content of the addItem function, but the constructor, I just want to know that the addItem function is called.

There is a similar question here, but for some reason is not working for me. If I write this test:

describe("Menu", function() {
  it("Test constructor", function() {
    spyOn(Menu.prototype,'addItem');
    var newMenu = new menu();
  }
});

and I always get:

ReferenceError: Can't find variable: Menu in file:///home/whatever/library-test/spec/MenuSpec.js

I don't really know why is this happening, is the test code wrong or is that I've chosen a bad approach for creating my testable library code?

Community
  • 1
  • 1
namelivia
  • 2,657
  • 1
  • 21
  • 24
  • 1
    Your first snipped should return something (so it is assigned to `window.menu`). Try adding `return menu;` right before the line with `}());`. – acdcjunior Apr 09 '15 at 18:55
  • 2
    Actually, just returning something to `menu` will not be enough make it work. Look, all your code is being executed inside a closure, so the `Menu` never makes it to the global scope, as the jasmine test function is expecting it to be. – acdcjunior Apr 09 '15 at 18:58
  • The return menu was a copypaste mistake, I've fixed it. – namelivia Apr 09 '15 at 18:59
  • 1
    Correct; `Menu` doesn't exist outside your IIFE. – Dave Newton Apr 09 '15 at 19:00
  • But is it good or bad? I read it was a good practice to encapsulate the library code inside a closure, but does it make untestable? – namelivia Apr 09 '15 at 19:01
  • 2
    It makes referencing enclosed types impossible, whether or not it makes your class untestable depends on your class--there are a lot of ways to test things. In this case I'm not sure why `Menu` is enclosed where it is--if it's its own "thing" then it should be in its own module, not wrapped up in an IIFE. – Dave Newton Apr 09 '15 at 19:04
  • 1
    You are making life sooo much harder for yourself. The purpose of IIFE is not to pollute the global namespace, but now if you want something being exposed, what's the point in hiding it in the first place? – Lim H. Apr 09 '15 at 19:05
  • I get it, I'll read about it. Thanks! – namelivia Apr 09 '15 at 19:25

0 Answers0