Writing tests with Jasmine Standalone


In this 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.


// JavaScript Animal class

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


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

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

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



// 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







The spec file contains the test cases 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() {
      expect(cat.eat("fish")).toEqual("Cat eating fish");
    it("should be able to speak meeeooowww", function() {



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>
  <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>





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.