简体   繁体   中英

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

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]; } } } 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM