2

How to write Unit Test Case for below javascript function using Jasmine?

function GetURLParameter(sParam) {
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return sParameterName[1];
        }
    }
}
James Z
  • 12,209
  • 10
  • 24
  • 44
Mandeep Rehal
  • 93
  • 2
  • 4
  • 11

1 Answers1

0

As per jasmine documentation, jasmine contains two things describe and specs.

The describe function is for grouping related specs, typically each test file has one at the top level. The string parameter is for naming the collection of specs, and will be concatenated with specs to make a spec's full name. This aids in finding specs in a large suite. If you name them well, your specs read as full sentences in traditional BDD style.

Specs are defined by calling the global Jasmine function it, which, like describe takes a string and a function. The string is the title of the spec and the function is the spec, or test. A spec contains one or more expectations that test the state of the code. An expectation in Jasmine is an assertion that is either true or false. A spec with all true expectations is a passing spec. A spec with one or more false expectations is a failing spec.

Read more here

You can do something like this:

function GetURLParameter(sParam) {   
    var sPageURL = "email=someone@example.com"; //replace it with your
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return sParameterName[1];
        }
    }
}
// specs code
describe("check for url", function() {
  //defining it should be something
  it("should be defined", function() {
    expect(GetURLParameter).toBeDefined();
  });
  
  it("should run", function() {
    expect(GetURLParameter('email')).toEqual("someone@example.com");
  });
  
 

});

var NOT_IMPLEMENTED = undefined;

// load jasmine htmlReporter
(function() {
  var env = jasmine.getEnv();
  env.addReporter(new jasmine.HtmlReporter());
  env.execute();
}());
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<link href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
Just code
  • 13,553
  • 10
  • 51
  • 93