Jasmine in Browser

Download the standalone distribution (zip file) from https://github.com/jasmine/jasmine/releases and extract it.

Inside the extracted directory, there are two files - an MIT.LICENSE file and a SpecRunner.html file - and three directories - /lib, /spec and /src. The SpecRunner.html file executes the included specs when run in browser. The /lib directory contains Jasmine library, the JavaScript code to be tested goes inside the /src directory, and the specs inside the /spec directory.

Consider a JavaScript file test.js, containing two functions, pi() and sin(). This file is saved inside the src directory.

        
          function pi() {
            return 3.141;
          }
          function sin(x) {
            return Math.sin(x);
          }
        
      

We write the specs in Jasmine (below) to check that the value of π returned by pi() equals 3.141 and the value of the trigonometric ratio sine is always ≤ 1 and ≥ -1, for any random number generated between 1 and 100. We name this spec file test.spec.js and save it inside the spec directory

        
          describe("Value of pi", function() {
            it("is equal to 3.141", function() {
              expect(pi()).toEqual(3.141);
            });
          });
          describe("Value of sine", function() {
            it("is less than or equal to 1", function() {
              expect(sin(Math.floor((Math.random() * 100) + 1)) 
                <= 1).toBeTruthy();
            });
            it("is greater than or equal to -11", function() {
              expect(sin(Math.floor((Math.random() * 100) + 1)) 
                < -1).toBeFalsy();
            });
          });
        
      

Edit the SpecRunner.html file just to include test.js, the JS code to be tested, and the spec file test.spec.js. 2.4.1 is just the standalone version number used for this tutorial and thus it can vary

        
          <!DOCTYPE html>
          <html>
          <head>
            <meta charset="utf-8">
            <title>Jasmine Spec Runner v3.4.0</title>
            <link rel="shortcut icon" type="image/png" 
              href="lib/jasmine-3.4.0/jasmine_favicon.png">
            <link rel="stylesheet" href="lib/jasmine-3.4.0/jasmine.css">
            <script src="lib/jasmine-3.4.0/jasmine.js"></script> 
            <script src="lib/jasmine-3.4.0/jasmine-html.js">
            </script>
            <script src="lib/jasmine-3.4.0/boot.js"></script> 
            <!-- include source files here -->
            <script type="text/javascript" src="src/test.js">
            </script> 
            <!-- include spec files here --> 
            <script type="text/javascript" src="spec/test.spec.js">
            </script>
          </head>
          <body>
          </body>
          </html>
        
      

Open SpecRunner.html file in a browser and run the specs.