Srisa Srisa - 18 days ago 5
HTML Question

How to test function expression in jasmine

I am learning jasmine. Trying to test the following code.

Not sure how can i create a personModule object in jasmine and how to use and test it . Any help would be great.



window.onload = function () {
var module = personModule;
module.init();
}

var personModule = (function (module) {
module.getName = function () {
alert("my name" + "is Xyz");
}

module.init = function () {
alert("in init");
}
return module;
})(personModule||{});





Can someone please help me on this

Thanks

Answer

I dont think there is anything specific to jasmine in your code. Its a regular function in JS.

Also, your methods doesn't have anything to test as you only have alerts inside the functions.

You probably want to test if your getName returns something. like

getName: function(){
  return "some name";
}

then you could assert and test.

assert(getName()).toBe("some name");

In your code I dont see a need for you to use IIFE with personModule || {}

You could refactor your code like below to make it a testable module.

window.onload = function() {
  personModule.init();
}

var personModule = (function() {
  var module = {};
  module.getName = function() {
    return "my name is Xyz";
  }

  module.init = function() {
    alert("in init");
    return true;
  }
  return module;
})();

You could have your jasmine tests as below.

describe("Test Person Module", function() {
  it("Name to return default value", function() {
    expect(personModule.getName()).toBe("my name is Xyz");
  });

  it("Init to be Succesful", function() {
    expect(personModule.init()).toBe(true);
  });
});