Writing tests with Jasmine Standalone

In this post post we will learn how to write sample jasmine tests.
Let’s write some example code and then test it with Jasmine. We will code
for two classes Animal and Cat in Javascript. I will keep the object code
and test code very simple.

Animal.js

// JavaScript Animal class

function Animal(name) {
    this._name = name;
}

Animal.prototype._name;


Animal.prototype.getName = function() {
    return this._name;
}

Animal.prototype.eat = function(food) {
    return "Animal has eaten " + food;
}

Animal.prototype.speak = function() {
    return "";
}

 

Cat.js

// JavaScript Cat class

function Cat(name) {
    Animal.call(this, name);
 }
 
 Cat.prototype.speak = function() {
     return "meeeooowww";
 }
 
 Cat.prototype.eat = function(food) {
     return "Cat eating " + food
 }

 

 

CatSpec.js

 

 

 

The spec file contains the testcases to be automated. Simple tests to test the cat object are added in the spec file.

describe("Cat", function() {
    var cat;
   
    beforeEach(function() {
      cat = new Cat();
    });
  
    it("should be able to eat fish", function() {
      cat.eat("fish");
      expect(cat.eat("fish")).toEqual("Cat eating fish");
    });
  
    it("should be able to speak meeeooowww", function() {
      cat.speak();
      expect(cat.speak()).toEqual("meeeooowww");
    });
});
  
   

 

SpecRunner.html

Now add the source and spec files to the spec runner html code. Please make sure you give the right directory paths for the source and test spec files.

<!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 src="src/Cat.js"></script>
  <script src="src/Animal.js"></script>

  <!-- include spec files here... -->
  <script src="spec/SpecHelper.js"></script>
  <script src="spec/CatSpec.js"></script>

</head>

<body>
</body>
</html>

 

 

Save the spec runner html file and launch it using your favorite browser.

You can see that Jasmine has run two specs and both the specs have been passed and no failures.

Related Posts