Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Jasmine Cookbook
Jasmine Cookbook

Jasmine Cookbook: Over 35 recipes to design and develop Jasmine tests to produce world-class JavaScript applications

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Jasmine Cookbook

Chapter 1. Getting Started with Jasmine Framework

In this chapter, we will cover:

  • Writing your first Jasmine test
  • Adding specs to your Jasmine test
  • Adding expectations and matchers to the test
  • Applying different matchers to the Jasmine test
  • Applying setup and teardown functions to the Jasmine test
  • Using the "this" keyword

Introduction

Nowadays, JavaScript has become the de facto programming language to build and empower frontend/web applications. We can use JavaScript to develop simple or complex applications. However, applications in production are often vulnerable to bugs caused by design inconsistencies, logical implementation errors, and similar issues. For this reason, it is usually difficult to predict how applications will behave in real-time environments, which leads to unexpected behavior, non-availability of applications, or outages for short or long durations. This generates lack of confidence and dissatisfaction among application users. Also, high cost is often associated with fixing the production bugs. Therefore, there is a need to develop applications that are of a high quality and that offer high availability.

Jasmine plays a vital role to establish effective development process by applying efficient testing processes. Jasmine is an excellent framework for testing JavaScript code both in browser and on the server side. We well use version 2.0.1 of Jasmine in this book. In this chapter, we will cover how tests can be written for JavaScript code using the Jasmine framework. You will also learn how various Jasmine matchers play a pivotal role for writing the tests.

Writing your first Jasmine test

To write our first Jasmine test, we will use a program that will calculate the factorial of a given number.

"As a user, I want to validate/evaluate factorial functionality so that I can get the exact factorial value for a given number."

Let's consider some scenarios in the current context:

  • Scenario-1: Factorial value should be evaluated for a given positive number
  • Scenario-2: A 'null' value should be returned for negative numbers

Getting ready

To start writing Jasmine tests, you need to download Jasmine from the official website. Download the Jasmine Standalone release (that is, jasmine-standalone-2.x.x.zip) from the following website:

https://github.com/pivotal/jasmine/releases

How to do it...

To start a Jasmine test, perform the following steps:

  1. First, you need to create a spec file under the /spec folder. Create the Factorial_spec.js file and code the following lines:
    describe("Factorial", function() {
    
    });
  2. Next, add the following code to Factorial_spec.js:
    describe("Factorial", function() {
        it("should get factorial of given number", function() {
    
        });
      });
  3. Further, add another it block to your Jasmine test and use the following code:
    describe("Factorial", function() {
        it("should get factorial of given number", function() {
    
        });
        it("should return null value for passing negative number or less/more than one argument", function() {
    
        });
      });
  4. To implement the factorial functionality, we need JavaScript code. So, create a Factorial.js file and put it under the /src folder:
    function factorial(num)
    {
      if (num==1 && factorial.arguments.length == 1) {
        return 1;
      }
      else if (num >1 && factorial.arguments.length == 1) {
        return num*factorial(num-1);
      }
      else {
        return null;  /* Validate if parameter is passed as negative number or less/more than one parameter */
      }
    }
  5. Now, to test the Factorial functionality, we will implement it in the Jasmine test using the following code:
    describe("Factorial", function() {
        it("should get factorial of given number", function() {
          expect(factorial(3)).toEqual(6);
        });
        it("should return null value for passing negative number or less/more than one arguments", function() {
          expect(factorial(-3)).toEqual(null);
        });
    });

    In the preceding code snapshot, notice that we implemented both scenarios with the help of assertions using expectations and matchers.

    Note

    An expectation in Jasmine is an assertion that is either true or false.

    Jasmine provides the expect function to test the code. It accepts a value called the actual. Furthermore, it is chained with the matcher function, which accepts the expected value. In current context, the matcher function is toEqual.

    To learn more about expectation and matchers, refer to the recipes Adding expectations and matchers to the test and Applying different matchers to the Jasmine test in this chapter.

  6. To run Jasmine's spec for both scenarios, we need to add the reference of the JavaScript file (that is, Factorial.js) and spec file (that is, Factorial_spec.js) to the test runner (that is, SpecRunner.html file). Use the following code:
    <!-- include source files here... -->
      <script type="text/javascript" src="src/Factorial.js"></script>
    
    <!-- include spec files here... -->
      <script type="text/javascript" src="spec/Factorial_spec.js"></script>

    Note

    In your test runner (that is, SpecRunner.html), you can see the reference to different source files (that is, Player.js and Sonj.js) and spec files (that is, SpecHelper.js and PlayerSpec.js). These files are shipped along with the Jasmine standalone release. Here, you need to remove the references to these files and add the reference to your source file (that is, Factorial.js) and spec file (that is, Factorial_spec.js).

  7. Now, execute the test suite by opening the Jasmine runner (that is SpecRunner.html) in a browser, and you will see something similar to the following screenshot, which will let you know that the tests have run successfully:
    How to do it...

    The SpecRunner.html file acts as a test runner for Jasmine tests. We can also call it the Jasmine runner. Indeed, from now onwards, throughout this book, we will refer to the SpecRunner.html file as the Jasmine runner.

How it works...

Let's take a look at what we did in this recipe.

In step 1, we defined the test suite using the describe function. It is a global Jasmine function and accepts the following two parameters:

  • String: Usually, we mention this parameter as the name of the test suite corresponding to the functionality that is currently being tested. A test suite represents a specific functionality or component of our application. In our case, it is Factorial.
  • Function: This is a block of code that implements the suite. You can create n suites corresponding to functionality/application components, as needed.

In step 2, we defined the condition of scenario 1 by implementing the it block inside the describe block. It's also a global Jasmine function that accepts two parameters, that is, a string and a function:

  • String: This is the title of the spec. In our case, we created the spec as should get factorial of given number for scenario 1.
  • Function: Here, we write Jasmine code (test code or the actual 'spec'), corresponding to the spec title to test the JavaScript code.

In step 3, we defined another condition for scenario 2 by adding a second spec using an additional it block. You can define as many specs within a test suite as your test requires.

In step 4, to test the JavaScript code, we created the Factorial.js file and wrote code for factorial functionality. We defined the conditions for scenario 1 and scenario 2 in the factorial function.

In step 5, we passed a value to the expect (that is, the expectation) function, which needs to be tested; this value is called the actual value. Furthermore, the expect function is chained to the matcher function, which takes the expected value. On the basis of actual versus expected value, it reports to Jasmine that the spec has either passed or failed.

In step 6, to test and execute the JavaScript code, we included the reference of the JavaScript file (Factorial.js) and the corresponding spec file (Factorial_spec.js) in the SpecRunner.html file.

See also

  • To understand more about specs and how to apply expectations and matchers, refer to the recipes Adding specs to your Jasmine test and Adding expectations and matchers to the test.

    Note

    Jasmine is a Behavior-Driven Development (BDD) framework. However, for now, we are not following the BDD process to write Jasmine tests as it is outside the scope of this recipe. In Chapter 2, Jasmine with TDD and BDD Processes, we will discuss in detail how Jasmine test and application code is developed alongside using Test-Driven Development (TDD) and BDD process.

Adding specs to your Jasmine test

To write specs for a given requirement, let's consider the following example of <ABC> company.

<ABC> is a product-based company that develops cutting edge software/products for sales and inventory control systems. Currently, they have one base product that offers all the standard features required of a sales and inventory system (for example, generating sales invoice, sales return/issue, vendor analysis, billing management, budgeting, finance, stock update, and so on). They also customize base products as per customers' specific needs. Recently, the <ABC> company has provided software to a spare parts company and the customer is performing acceptance testing for the inventory system.

"As a Store Administrator, I want to update stock on every new transaction so that I can get the balance/stock in hand for further usage."

Let's consider some scenarios in the current context, that is, updating inventory stock in the event of any new transaction:

  • Scenario-1: Inventory Stock should be updated on account of item(s) sale or issue of item(s)
  • Scenario-2: Inventory stock should be updated on return of any item(s)
  • Scenario-3: Inventory stocks should be updated on receiving/procuring new item(s)

How to do it…

To write specs to a Jasmine test, perform the following steps:

  1. First, you need to create a spec file under the /spec folder. Create the InventoryStock_spec.js file and code the following lines:
    describe("Inventory Stock", function() {
    //Scenario – 1
      
    });
  2. Next, use the following code to define specs:
    describe("Inventory Stock", function() {
    //Scenario – 1
        it("Inventory Stock should be updated on sale/issue of an item", function() {
    
        });
      });
  3. Now, to run the spec defined in the previous step, we need to add the reference of the spec file (that is, InventoryStock_spec.js) to the Jasmine runner (that is, SpecRunner.html file):
    <!-- include spec files here... -->
      <script type="text/javascript" src="spec/InventoryStock_spec.js"></script>
  4. To execute the test suite, open the Jasmine runner in a browser and you will see the spec results, as shown in the following screenshot:
    How to do it…

    You can see two things from the execution results:

    • The spec is prefixed with SPEC HAS NO EXPECTATION.
    • The spec passes even if we do not specify any expectation within the it block. In Jasmine, we need to implement an assertion to make the spec pass or fail. An assertion is a comparison between two values/expression that results in a Boolean value. A spec will only be considered passed if the assertion returns the Boolean value as true.
  5. Next, use the following code to optimize step 2:
          describe("Inventory Stock", function() {
            //Scenario - 1
    it("Inventory Stock should be updated on sale of item", function() {
    
              });
    it("Inventory Stock should be updated on issue of an item within organization", function() {
    
              });
          });

    In the preceding code snapshot, you can notice that we further divided the spec into two specs where the first spec represents a sale and the other spec is for the issuing of an item. Now, both the specs represent unique behavior.

    Tip

    It is highly recommended to refactor the requirement up to granular level. This will help you to analyze test execution results. Moreover, you (and other stakeholders) can easily identify root causes and map precisely the failed specs with application code.

  6. Next, let's use the following test code to implement the specs functionality:
          describe("Inventory Stock", function() {
          //Scenario - 1
    it("Inventory Stock should be updated on sale of item", function() {
                var stockinhand_item1=11;
                var item1 = 1;
                var transaction = 'SALE';
                expect(stockinhand_item1-item1).toEqual(10);
              });
    it("Inventory Stock should be updated on issue of an item within organization", function() {
                var stockinhand_item1=11;
                var item1 = 1;
                var transaction = 'ISSUE';
                expect(stockinhand_item1-item1).toEqual(10);
              });
          });
  7. Now when you run the spec file, you will see that both the specs pass for scenario 1, as shown in the following screenshot:
    How to do it…
  8. Now, use the following code to define and implement the specs for scenario 2 and scenario 3:
    describe("Inventory Stock", function() {
      //Scenario - 1
      it("Inventory Stock should be updated on sale of item", function() {
          var stockinhand_item1=11;
          var item1 = 1;
          var transaction = 'SALE';
          expect(stockinhand_item1-item1).toEqual(10);
        });
        it("Inventory Stock should be updated on issue of an item within organization", function() {
          var stockinhand_item1=11;
          var item1 = 1;
          var transaction = 'ISSUE';
          expect(stockinhand_item1-item1).toEqual(10);
        });
        //Scenario - 2
        it("Inventory Stock should be updated on return of any item", function() {
          var stockinhand_item1=11;
          var item1 = 1;
          var transaction = 'SALE RETURN';
          expect(stockinhand_item1+item1).toEqual(12);
        });
        //Scenario - 3
        it("Inventory Stock should be updated on receiving or procuring new item", function() {
          var stockinhand_item1=11;
          var item1 = 1;
          var transaction = 'PROCUREMENT';
          expect(stockinhand_item1+item1).toEqual(12);
        });
    });
  9. Finally, run the spec file (InventoryStock_spec.js) using the Jasmine runner. You will see the test execution results, as shown in the following screenshot indicating the success of all four specs:
    How to do it…

How it works...

Let's understand what we did throughout this recipe.

In step 1, we created a spec file and defined the name of the test suite corresponding to the functionality, which is currently being tested. In the present scenario, we named it as Inventory Stock.

In steps 2 to 4, we created the spec to define scenario 1 and executed the scenario using the Jasmine runner. In this scenario, we defined specs to validate whether the stock is being updated (or not) on account of the sale of an item or the issue of an item to a person/department within the organization.

In step 5, we further refactored the specs of scenario 1 to make them more understandable and granular.

In steps 6 and 7, we implemented the test code for scenario 1 corresponding to specs.

In steps 8 and 9, following the same pattern, we implemented the test code for scenarios 2 and 3.

See also

  • To gain a deeper understanding about how to design and write specs, refer to the recipe Defining nested suites to write more meaningful specs in Chapter 2, Jasmine with TDD and BDD Processes.

Adding expectations and matchers to the test

Inside the it block, you can write all the test code that is required to test the application/JavaScript code by applying assertions using expectations and matchers. Expectations are built with an expect function, which takes a value called actual. It is further chained with the matcher function(s), which takes the expected value. Each matcher implements a Boolean expression depending on the actual and expected value. It is responsible for reporting to Jasmine whether the expectation is true or false. Jasmine passes or fails the spec on the basis of the Boolean value returned by the matcher. In this recipe, you will learn how assertions are applied using the toBe matcher. You will also learn how negative assertions are applied.

To understand this recipe, assume that you are developing a bank application to track details of fixed deposit, recurring deposit, and all other financial transactions.

"As a finance administrator, I want to track all financial transactions so that I can categorize them for further assessment/processing."

Let's consider the following scenarios in the current context, that is, all financial transactions should be tracked and categorized:

  • Scenario-1: Deposit should be of the fixed Deposit (FD) type on locking amount for a fix period
  • Scenario-2: Deposit should be of the Recurring Deposit (RD) type for an amount deposited with regular frequency (that is, monthly, quarterly, half-yearly, yearly, and so on)

How to do it…

You need to perform the following steps to apply the toBe matcher on these scenarios:

  1. Create the Deposit_spec.js file under the /spec folder and code the following lines:
    describe("Bank Deposit ", function() {
    //Scenario 1
      
    });
  2. Next, use the following code to define specs for scenario 1 and scenario 2:
    describe("Bank Deposit",function(){
      //Scenario 1
      it("should be considered as FD on locking amount for a fixed period", function(){
    
      });
      //Scenario 2
      it("should be considered as RD on depositing amount on regular frequency", function(){
    
      });  
    });
  3. To implement scenario 1 and scenario 2, we need JavaScript code. So, create the Deposit.js file, put it under the /src folder, and use the following code:
    function Deposit(Frequency) {
      this.Type= Frequency;
    };
    
    Deposit.prototype.BankDeposit = function(){
      switch (this.Type) {
      case "FIX" :  
            return "FD";
            break;
      case "RECURRING" :  
            return "RD";
            break;
      };
    };
  4. Next, use the following code to implement specs for scenario 1 and scenario 2:
    describe("Bank Deposit",function(){
      //Scenario -1
      it("should be considered as FD on locking amount for a fix period", function(){
        var MyDeposit = new Deposit("FIX");
        DepositType = MyDeposit.BankDeposit();
        expect(DepositType).toBe("FD");
      });
      //Scenario -2
      it("should be considered as RD on depositing amount on regular frequency", function(){
        var MyDeposit = new Deposit("RECURRING");
        DepositType = MyDeposit.BankDeposit();
        expect(DepositType).toBe("RD");
      });  
    });
  5. Now, run the spec file (Deposit_spec.js) using the Jasmine runner and you will see that tests pass for both the scenarios, as shown in the following screenshot:
    How to do it…
  6. Now, to apply negative assertions on both of the scenarios, consider the following code:
    describe("Bank Deposit",function(){
      //Scenario -1
      it("should be considered as FD on locking amount for a fix period", function(){
        var MyDeposit = new Deposit("FIX");
        DepositType = MyDeposit.BankDeposit();
        expect(DepositType).toBe("FD");
        expect(DepositType).not.toBe("FD");
      });
      //Scenario -2
      it("should be considered as RD on depositing amount on regular frequency", function(){
        var MyDeposit = new Deposit("RECURRING");
        DepositType = MyDeposit.BankDeposit();
        expect(DepositType).toBe("RD");
        expect(DepositType).not.toBe("RD");
      });  
    });

    In the preceding code snapshot, notice that we implemented the negative assertion by chaining the call to expect with a not before calling the matcher.

  7. Now, run the spec file (Deposit_spec.js) using the Jasmine runner and you will see that it indicates that both the tests fail, as shown in the following screenshot:
    How to do it…

    In the preceding screenshot, notice that we have provided wrong values corresponding to negative assertions.

  8. Now, use the following code to pass both the tests:
    describe("Bank Deposit",function(){
      //Scenario -1
      it("should be considered as FD on locking amount for a fix period", function(){
        var MyDeposit = new Deposit("FIX");
        DepositType = MyDeposit.BankDeposit();
        expect(DepositType).toBe("FD");
        expect(DepositType).not.toBe("RD");
        expect(DepositType).not.toBe("Any value Other than 'FD' ");
      });
      //Scenario -2
      it("should be considered as RD on depositing amount on regular frequency", function(){
        var MyDeposit = new Deposit("RECURRING");
        DepositType = MyDeposit.BankDeposit();
        expect(DepositType).toBe("RD");
        expect(DepositType).not.toBe("FD");
        expect(DepositType).not.toBe("Any value Other than 'RD' ");
      });  
    });
  9. Finally, run the spec file (Deposit_spec.js) using the Jasmine runner and you will see that it indicates that both the tests pass, as shown in the following screenshot:
    How to do it…

How it works...

In step 1 and step 2, we defined the name of the suite and specs for scenario 1 and scenario 2.

In step 3, JavaScript code is provided to implement Jasmine tests for both the scenarios. Here, we defined the object construction function with one parameter (that is, frequency) to identify the type of deposit. Also, we created a BankDeposit() function for the deposit object using JavaScript prototype property.

In step 4, we implemented the test code corresponding to specs within the it block to test the code. First, we created the object of deposit and then invoked the BankDeposit() function of the deposit object to get the deposit type. Finally, we implemented the assertion to compare the actual and expected value using the toBe matcher.

In steps 6 through 9, we implemented a negative assertion by chaining the call to expect with a not before calling the matcher. We also looked at how Jasmine tests pass/fail using the different values with negative assertion.

Applying different matchers to the Jasmine test

Jasmine provides a rich set of matchers to test JavaScript code. In this recipe, you will learn to apply various matchers in different situations.

To understand this recipe, let's assume that you are developing an application and you have to implement test code for various scenarios by applying different Jasmine matchers.

"As a developer, I want to apply different Jasmine matchers so that I can implement a test condition successfully."

Let's consider some scenarios in the preceding context, that is, where Jasmine matchers should be applied for different test conditions:

  • Scenario-1: The 'toMatch' matcher should be applied successfully for regular expressions
  • Scenario-2: The 'toEqual' matcher should be applied successfully for literals, variables, and objects
  • Scenario-3: The 'toBe' matcher should be applied successfully for literals, variables, and objects
  • Scenario-4: The 'toBeDefined' matcher should be applied successfully to compares against defined
  • Scenario-5: The 'toBeUndefined' matcher should be applied successfully to compares against undefined
  • Scenario-6: The 'toBeNull' matcher should be applied successfully to compare against null
  • Scenario-7: The 'toBeTruthy' matcher should be applied successfully for Boolean casting testing
  • Scenario-8: The 'toBeFalsy' matcher should be applied successfully for Boolean casting testing
  • Scenario-9: The 'toContain' matcher should be applied successfully for finding an item in an array
  • Scenario-10: The 'toBeLessThan' matcher should be applied successfully for mathematical comparisons
  • Scenario-11: The 'toBeGreaterThan' matcher should be applied successfully for mathematical comparisons
  • Scenario-12: The 'toBeCloseTo' matcher should be applied for precision math comparison

How to do it…

To apply different matchers to your Jasmine tests, you need to perform the following steps in the preceding scenarios:

  1. Create the JasmineMatchers_spec.js file under the /spec folder and code the following lines:
    describe("Jasmine Matchers", function() {
    //Scenario – 1
      
    });
  2. Now, use the following code to define and implement the spec for scenario 1 using the toMatch matcher:
    describe("Jasmine Matchers",function(){
      //Scenario -1
      it("'toMatch' matcher should be applied successfully for regular expressions", function() {
          var strString1 = "Packt Cookbooks are an excellent source of learning";
          var strPhone = "001-789-56-67";
          expect(strString1).toMatch(/Cookbooks/);
          expect(strString1).toMatch(/cookbooks/i);
          expect(strString1).not.toMatch(/Java/);
          expect(strPhone).toMatch(/\d{3}-\d{3}-\d{2}-\d{2}/);
        });
    });

    Note

    A regular expression is a sequence of characters that forms a search pattern. Search patterns can be defined based on a single character, combination of characters/strings, or more complicated patterns. To explore more about regular expressions in greater depth, visit the following website:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

  3. The next step is to run the spec file (JasmineMatchers_spec.js) using the Jasmine runner, and you will see that the test passes, as shown in the following screenshot:
    How to do it…
  4. Now, use following code to implement scenario 2 and scenario 3:
    describe("Jasmine Matchers",function(){
    
      //Scenario - 2
      describe("toEqual matcher should be applied successfully", function(){
        it("if numbers are equal", function() {
            var intVar = 15;
            expect(intVar).toEqual(15);
          });
        it("if strings are equal", function() {
            var strVar = "Jasmine Cookbook";    
            expect(strVar).toEqual("Jasmine Cookbook");
          });
    
        it("if objects are equal", function() {
            var MyObectj1 = {a: 12, b: 13};
            var MyObectj2 = {a: 12, b: 13};    
            expect(MyObectj1).toEqual(MyObectj2);
            expect(MyObectj1.a).toEqual(MyObectj2.a);
            expect(MyObectj1.a).not.toEqual(MyObectj2.b);
          });
        it("if arrays are equal", function() {
            expect([8, 9, 10]).toEqual([8, 9, 10]);
            expect([8, 9, 10, 11]).not.toEqual([8, 9, 10]);
          });
      });
    
      //Scenario - 3
      it("toBe matcher should be applied successfully for literals, variables and objects", function() {
          var MyObj = {foo: "foo"};
          var MySameObj = {foo: "foo"};
          var strVar = "Jasmine Cookbook";
          var myArr = [8, 9, 10];
          expect(MyObj).toBe(MyObj);
          expect(MySameObj).not.toBe(MyObj);
    
      expect(MySameObj).toEqual(MyObj);
          expect(strVar).toBe("Jasmine Cookbook");
          expect(myArr).toEqual([8, 9, 10]);
          expect(myArr).not.toBe([8, 9, 10]);
      });
    });

    In the preceding code snapshot, notice that we created two objects (that is, MyObj and MySameObj). Both look similar and equal, but they are two different objects with exactly the same attributes. Furthermore, you can observe the behavior of the toBe and toEqual matchers. Here, while comparing both the objects, the assertion value will return true with the toEqual matcher and false with the toBe matcher. Also, this is true for an array object (that is, myArr).

    Note

    The toEqual() matcher checks equivalence. On the other hand, the toBe() matcher ensures that they are the exact same objects.

  5. Next, run the spec file (JasmineMatchers_spec.js) for scenario 2 and scenario 3 using the Jasmine runner. The tests should run successfully, as shown in the following screenshot:
    How to do it…
  6. Use the following code to implement scenario 4:
    describe("Jasmine Matchers",function(){
      //Scenario - 4
      it("toBeDefined should be applied successfully to compares against defined.", function() {
            var MyObj = {
              foo: "foo"
            };
            var Myfunction = (function() {})();
            var strUndefined;
            expect("Jasmine Cookbooks").toBeDefined();
            expect(MyObj).toBeDefined();
            expect(MyObj.foo).toBeDefined();
            expect(Myfunction).not.toBeDefined();
            expect(strUndefined).not.toBeDefined();
          
        });
    });

    Note

    Undefined is a built-in JavaScript type. In JavaScript, if we declare a variable without assigning a value, its type is undefined. Also, JavaScript functions without a return statement or with empty return statements return undefined. To learn more about undefined and how it works, visit the following website:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

  7. Use the following code to implement scenario 5:
    describe("Jasmine Matchers",function(){
      //Scenario - 5
      it("toBeUndefined should be applied successfully to compares against undefined.", function() {
          var MyObj = {
                  foo: "foo"
                };
          var Myfunction = (function() {})();
          var strUndefined;
            expect(MyObj).not.toBeUndefined();
            expect(MyObj.foo).not.toBeUndefined();      
            expect(Myfunction).toBeUndefined();
            expect(strUndefined).toBeUndefined();
      });
    });
  8. Now, run the spec file (for scenario 4 and 5) with the Jasmine runner. You will see that all Jasmine tests pass for both the scenarios, as shown in the following screenshot:
    How to do it…
  9. To implement scenario 6, use the following code:
    describe("Jasmine Matchers",function(){
       //Scenario - 6
        it("toBeNull matcher should be applied successfully to compare against null", function() {
            var nullValue = null;
            var valueUndefined;
            var notNull = "notNull";
            expect(null).toBeNull();
            expect(nullValue).toBeNull();
            expect(valueUndefined).not.toBeNull();
            expect(notNull).not.toBeNull();
          });   
    });
  10. To see how Jasmine handles null values using the toBeNull matcher, run the spec file (only for scenario 6) with the Jasmine runner. You will see that the test passes, as shown in the following screenshot:
    How to do it…
  11. Use the following code to implement scenarios 7 and 8:
    describe("Jasmine Matchers",function(){
        //Scenario - 7
           it("toBeTruthy matcher should be applied successfully for Boolean casting testing", function() {
            var MyVar1=12, MyVar2 = "True for Non Empty Strings";
            expect(true).toBeTruthy();
            expect("Jasmine Cookbook").toBeTruthy();
            expect(MyVar1).toBeTruthy();
            expect(MyVar2).toBeTruthy();
        });
        //Scenario - 8
        it("toBeFalsy matcher should be applied successfully for Boolean casting testing", function() {
            var MyVar1=12, MyVar2 = "True for Non Empty Strings";
            expect(false).toBeFalsy();
            expect(null).toBeFalsy();
            expect(true).not.toBeFalsy();
            expect("Jasmine Cookbook").not.toBeFalsy();
            expect(MyVar1).not.toBeFalsy();
            expect(MyVar2).not.toBeFalsy();
        });
    });
  12. Next, run the spec file (for scenarios 7 and 8) with the Jasmine runner and you will see that both the Jasmine tests pass, as shown in the following screenshot:
    How to do it…
  13. Use the following code to implement scenario 9:
    describe("Jasmine Matchers",function(){
        it("toContain matcher should be applied successfully for finding an item in an Array", function() {
          var MyArray = ["Jasmine", "Cookbook", "JavaScript"];
            expect([1, 2, 3]).toContain(2);
            expect([1, 2, 3]).toContain(2,3);
            expect(MyArray).toContain("Cookbook");
            expect([1, 2, 3]).not.toContain(4);
            expect(MyArray).not.toContain("Java");
        });
    });
  14. Now, run the spec file (only for scenario 9) with the Jasmine runner and you will see that all the test conditions pass for scenario 9, as shown in the following screenshot:
    How to do it…
  15. Use the following code to implement scenarios 10 and 11:
    describe("Jasmine Matchers",function(){
        //Scenario - 10
        it("toBeLessThan matcher should be applied successfully for mathematical comparisons", function() {
            var pi = 3.1415926, g = 9.71; num1=5, num2=9;
            expect(pi).toBeLessThan(g);
            expect(num1).toBeLessThan(num2);
            expect(g).not.toBeLessThan(pi);
            expect(num2).not.toBeLessThan(num1);
        });
    
        //Scenario - 11
        it("toBeGreaterThan matcher should be applied successfully for mathematical comparisons", function() {
            var pi = 3.1415926, g = 9.71; num1=5, num2=6;
            expect(g).toBeGreaterThan(pi);
            expect(num2).toBeGreaterThan(num1);
            expect(pi).not.toBeGreaterThan(g);
            expect(num1).not.toBeGreaterThan(num2);
        });
    });
  16. Run the spec file (for scenarios 10 and 11) with the Jasmine runner and you will see that both the tests pass, as shown in the following screenshot:
    How to do it…
  17. To implement scenario 12, use the following code:
    describe("Jasmine Matchers",function(){
        it("toBeCloseTo matcher should be applied for precision math comparison", function() {
            var pi = 3.1415926, e = 2.78;
            expect(pi).not.toBeCloseTo(e);
            expect(pi).toBeCloseTo(e,0);
            expect(4.334).toBeCloseTo(4.334);
            expect(4.334).toBeCloseTo(4.3345,1);
            expect(4.334).toBeCloseTo(4.3345,2);
            expect(4.334).not.toBeCloseTo(4.3,2);
            expect(4.223).not.toBeCloseTo(4.22,3);
            expect(4.223).not.toBeCloseTo(4.22,4);
        });
    });
  18. Next, run the spec file (for scenario 12) with the Jasmine runner and you will see that all the test conditions pass:
    How to do it…
  19. Finally, to run all the 12 scenarios in one go, make a single spec file with the entire test code and run it (JasmineMatchers_spec.js) with the Jasmine runner. You will see that all the tests pass:
    How to do it…

How it works...

Let's take a look at the steps of this recipe.

In steps 1 to 3, we implemented scenario 1 with the toMatch matcher. It checks whether something is matched for a regular expression. You can use the toMatch matcher to test search patterns. In our case, we implemented the test code to find out search patterns with different regular expressions.

In steps 4 and 5, we defined the specs for scenario 2 and 3, and we implemented the test code corresponding to specs using the toEqual and toBe matchers. Here, notice that toBe looks similar to toEqual, but that is not the case. The toBe matcher returns the value true if the objects are equal. For example, in our case, MyObj and MySameObj look like the same objects, but in fact both are different objects with exactly the same attribute/behavior. Therefore, the assertion will return a true value with the toEqual matcher, but a false value with the toBe matcher.

In steps 6 to 8, we implemented scenarios 4 and 5 and saw how the toBeDefine and toBeUndefine matchers are applied to test JavaScript's Undefined type. In step 7, we first implemented a test condition for a non-empty string and two test conditions with object variable MyObj. We also implemented test conditions for the strUndefined variable and the MyFunction()function by applying negative assertions. Conversely, in step 8, we implemented test conditions with the object variable MyObj by applying negative assertions.

In step 9, we implemented test code for scenario 6 using the toBeNull matcher. In step 10, we saw test conditions pass for null values. However, we applied negative assertions to pass test conditions for not Null and Undefined values.

In step 11, we implemented scenario 7 and scenario 8 using the toBeTruthy and toBeFalsy matchers. We use the toBeTruthy matcher to check whether something returns/evaluates to true. Similarly, we use the toBeFalsy matcher to check whether something returns/evaluates to false. In our case, we applied the toBeTruthy matcher for true value, non-empty strings and numbers other than zero. Similarly, we applied toBeFalsy matcher to validate false, null, and empty strings.

In step 13, we implemented the test code for scenario 9 using the toContain matcher. Here, we implemented test conditions to find out an element(s)/item(s) of an array using the toContain matcher. Similarly, we implemented test conditions to check if an element/an item does did not exist in an array by applying negative assertions.

In step 15, we implemented scenario 10 and scenario 11 to compare mathematical values using the toBeLessThan and toBeGreaterThan matchers.

In step 17, we implemented scenario 12 using the toBeCloseTo matcher. This matcher is used to check whether a number is close to another number, up to a given level of decimal precision. In our case, we checked whether the expected number was equal to the actual number with a given level of decimal precision.

Applying setup and teardown functions to the Jasmine test

Very often, we reuse pieces of code across different scenarios. This is due to functionality dependencies among scenarios, preconditions, or some other requirements such as initialization/declaration of application/system variables or objects. This improves code redundancy and maintainability.

Generally, to avoid code duplication (across scenarios/Jasmine specs) and increase code reusability and readability, we use setup and teardown functions. Jasmine provides two global functions (that is, beforeEach and afterEach) corresponding to setup and teardown functions. We can initialize variables and write common code and preconditions under the beforeEach function. Similarly, the afterEach function can be used to reinitialize variables or reset preconditions. The beforeEach function is called once before each spec is run in the describe block, and the afterEach function is called once after each spec is run. Both the functions are very useful for refactoring and optimizing the common code.

Getting ready

You will learn this recipe with the help of the second recipe in this chapter. For more information, refer to the Adding specs to your Jasmine test recipe. In this recipe, we implemented three scenarios for a sales and inventory control system and created a spec file (InventoryStock_spec.js) with the test code.

How to do it…

To apply Setup and Teardown to the Jasmine test, you need to perform the following steps:

  1. First, you need to create a spec file (InventoryStockOptimizeCode_spec.js) under the /spec folder and get the following code from the spec file (InventoryStock_spec.js) created in the second recipe of this chapter, Adding specs to your Jasmine test:
    describe("Inventory Stock", function() {
      //Scenario - 1
      it("Inventory Stock should be updated on sale of item", function() {
            var stockinhand_item1=11;
            var item1 = 1;
          var transaction = "SALE";
          expect(stockinhand_item1-item1).toEqual(10);
        });
        it("Inventory Stock should be updated on issue of an item within organization", function() {
            var stockinhand_item1=11;
            var item1 = 1;
          var transaction = "ISSUE";
          expect(stockinhand_item1-item1).toEqual(10);
        });
    
        //Scenario - 2
        it("Inventory Stock should be updated on return of any item", function() {
            var stockinhand_item1=11;
            var item1 = 1;
          var transaction = "SALE RETURN";
          expect(stockinhand_item1+item1).toEqual(12);
        });
    
        //Scenario - 3
        it("Inventory Stock should be updated on receiving or procuring new item", function() {
            var stockinhand_item1=11;
            var item1 = 1;
          var transaction = "PROCUREMENT";
          expect(stockinhand_item1+item1).toEqual(12);
        });
    });

    In the preceding code snapshot, notice the code redundancy across the specs. Here, we declared and assigned value to variables in each spec separately.

  2. Next, refactor the code by applying the beforeEach and afterEach function by using the following code:
    describe("Inventory Stock", function() {
      var stockinhand_item1, item1;
      beforeEach(function() {
          stockinhand_item1=11, item1 = 1;
        console.log("beforeEach: Stock in hand for item1 before spec execution = " + stockinhand_item1);
        });
      afterEach(function() {
          stockinhand_item1=0, item1 = 0;
        console.log("afterEach: Stock in hand for item1 once spec executed = " + stockinhand_item1);
        });
    
      //Scenario - 1
      it("Inventory Stock should be updated on sale of an item", function() {    
          expect(stockinhand_item1-item1).toEqual(10);
        });
        it("Inventory Stock should be updated on issue of an item within organization", function() {
            expect(stockinhand_item1-item1).toEqual(10);
        });
    
        //Scenario - 2
        it("Inventory Stock should be updated on return of an item", function() {
            expect(stockinhand_item1+item1).toEqual(12);
        });
    
        //Scenario - 3
        it("Inventory Stock should be updated on receiving or procuring new item", function() {
            expect(stockinhand_item1+item1).toEqual(12);
        });
    });

    In the preceding code snapshot, notice that we declared the common variables and assigned the corresponding values in the beforeEach function. Here, we have written the code just for illustrative purpose and to understand the working of beforeEach and afterEach function.

  3. Finally, run the spec file (InventoryStockOptimizeCode_spec.js) using the Jasmine runner (that is, SpecRunner.html). You will see test execution results, as shown in the following screenshot, which indicates that all four specs are passing:
    How to do it…

    In your browser, if you go to the console window, you will see that the message defined with the console.log() method is printed four times, corresponding to each spec.

How it works...

In steps 1 to 3, we looked at how setup/teardown functions are applied to Jasmine tests using the beforeEach and afterEach functions. In step 2, we declared both the variables (stockinhand_item1 and item1) at the top-level scope, that is, the describe block. Here, we refactored the test code by moving the initialization code into a beforeEach function. Also, we reinitialized the value of variables using the afterEach function.

Using the "this" keyword

In Jasmine, we can also initialize and share the variables between beforeEach, it, and afterEach using the this keyword. In this recipe, we will see how the this keyword can be used within the beforeEach or afterEach functions.

Getting ready

You will learn this recipe with the help of the previous recipe. For more information, refer to the previous recipe, Applying setup and teardown functions to the Jasmine test. In this recipe, we refactor three scenarios for a sales and inventory control system by initializing/putting together common code in the beforeEach and afterEach functions.

How to do it…

To apply the this keyword to your Jasmine test, you need to perform the following steps:

  1. First, you need to create a spec file (InventoryStockOptimizeCode_With_this_spec.js) under the /spec folder and get the following code from the spec file (InventoryStockOptimizeCode_spec.js) created in the previous recipe, Adding specs to your Jasmine test:
    describe("Inventory Stock", function() {
      var stockinhand_item1, item1;
      beforeEach(function() {
          stockinhand_item1=11, item1 = 1;
        });
      afterEach(function() {
          stockinhand_item1=0, item1 = 0;
        });
      //Scenario - 1
      it("Inventory Stock should be updated on sale of an item", function() {    
          expect(stockinhand_item1-item1).toEqual(10);
        });
        it("Inventory Stock should be updated on issue of an item within organization", function() {
            expect(stockinhand_item1-item1).toEqual(10);
        });
        //Scenario - 2
        it("Inventory Stock should be updated on return of an item", function() {
            expect(stockinhand_item1+item1).toEqual(12);
        });
        //Scenario - 3
        it("Inventory Stock should be updated on receiving or procuring new item", function() {
            expect(stockinhand_item1+item1).toEqual(12);
        });
    });
  2. Now, apply the this keyword by using the following code:
    describe("Inventory Stock", function() {
      beforeEach(function() {
          this.stockinhand_item1=11, this.item1 = 1;
          console.log("beforeEach: Stock in hand for item1 before spec execution = " + this.stockinhand_item1);      
        });
      afterEach(function() {
          this.stockinhand_item1=0, this.item1 = 0;
          console.log("afterEach: Stock in hand for item1 once spec executed = " + this.stockinhand_item1);
        });
    
      //Scenario - 1
      it("Inventory Stock should be updated on sale of an item", function() {    
          this.transactionType = "SALE";
          expect(this.stockinhand_item1-this.item1).toEqual(10);
          expect(this.transactionType).toBeDefined();
        });
        it("Inventory Stock should be updated on issue of an item within organization", function() {
            expect(this.stockinhand_item1-this.item1).toEqual(10);
          expect(this.transactionType).toBeUndefined();
        });
    
        //Scenario - 2
        it("Inventory Stock should be updated on return of an item", function() {                expect(this.stockinhand_item1+this.item1).toEqual(12);
          expect(this.transactionType).toBeUndefined();
        });
    
        //Scenario - 3
        it("Inventory Stock should be updated on receiving or procuring new item", function() {        
      expect(this.stockinhand_item1+this.item1).toEqual(12);
      expect(this.transactionType).toBeUndefined();
        });
    });
  3. Finally, run the spec file (InventoryStockOptimizeCode_With_this_spec.js) using the Jasmine runner (that is, SpecRunner.html). You should see test execution results, as shown in the following screenshot, indicating that all four tests are passing:
    How to do it…

How it works...

In steps 1 to 3, we looked at how the this keyword is applied to a Jasmine test. In step 2, we removed the variable declaration from the top-level scope (that is, the describe block) and initialized/reinitialized the variables into the beforeEach/afterEach functions using the this keyword. Also, notice that this.transactionType is true only for the spec in which it was defined. For the other specs, the this.transactionType variable is considered as undefined. In other words, the scope of the this.transactionType variable is limited to the first spec only (that is, Inventory Stock should be updated on sale of an item). Conversely, the this.item1 variable is considered defined for all the specs because it is assigned in the beforeEach function that runs each time.

Left arrow icon Right arrow icon

Description

If you are a competent JavaScript developer who wants to design and implement tests using Jasmine in order to minimize bugs in the production environment, then this book is ideal for you. Some familiarity with unit testing and code coverage concepts such as branch coverage along with basic knowledge of Node.js, AngularJS, and CoffeeScript is required.

Who is this book for?

If you are a competent JavaScript developer who wants to design and implement tests using Jasmine in order to minimize bugs in the production environment, then this book is ideal for you. Some familiarity with unit testing and code coverage concepts such as branch coverage along with basic knowledge of Node.js, AngularJS, and CoffeeScript is required.

What you will learn

  • Develop JavaScript applications with Jasmine using the behaviordriven development (BDD) process
  • Apply custom matchers by enhancing your Jasmine tests to test specific features or functionality
  • Design Jasmine specs for jQuery and Ajax with HTML and JSON fixtures
  • Generate code coverage analysis for JavaScript code using Karma and Istanbul
  • Create Jasmine tests for CoffeeScript and AngularJS
  • Implement E2E (endtoend) Jasmine specs for JavaScript applications to simulate a realtime scenario
Estimated delivery fee Deliver to Austria

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 24, 2015
Length: 276 pages
Edition : 1st
Language : English
ISBN-13 : 9781784397166
Vendor :
Pivotal
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Austria

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Apr 24, 2015
Length: 276 pages
Edition : 1st
Language : English
ISBN-13 : 9781784397166
Vendor :
Pivotal
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 104.97
Jasmine Cookbook
€41.99
Jasmine JavaScript Testing Update
€29.99
Test-Driven JavaScript Development
€32.99
Total 104.97 Stars icon

Table of Contents

10 Chapters
1. Getting Started with Jasmine Framework Chevron down icon Chevron up icon
2. Jasmine with TDD and BDD Processes Chevron down icon Chevron up icon
3. Customizing Matchers and Jasmine Functions Chevron down icon Chevron up icon
4. Designing Specs from Requirement Chevron down icon Chevron up icon
5. Jasmine Spies Chevron down icon Chevron up icon
6. Jasmine with AJAX, jQuery, and Fixtures Chevron down icon Chevron up icon
7. Code Coverage with Jasmine Tests Chevron down icon Chevron up icon
8. Jasmine with Other Tools Chevron down icon Chevron up icon
9. Developing JavaScript Apps Using Jasmine – a Real-time Scenario Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(7 Ratings)
5 star 42.9%
4 star 42.9%
3 star 14.3%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Rene Lopez| Jun 04, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book covering the most of the common scenarios that you will find for test Javascript Apps in General.I actually was looking for a book that provided a concise and curated content for making tests for Javascript Apps and for me this is it, as it gives you kind of real business scenarios as examples for developing tests.We are always try to avoid testing and focus most on the time developing things but thanks to this book, you can follow a more TDD practices on my code and give more quality to it. A must reference for any JS Developer.
Amazon Verified review Amazon
Dipti Jun 15, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Book is designed to help both novice and advance users to understand and implement.It uses TDD and BDD process for the implementation, which makes implementation and execution of my project quite easy for new and existing code. It even has Code Coverage analysis explained using Karma and Istanbul tools. This book gives us a fair idea about the usage of Jasmine Spies from E2E perspective, Jasmine tests with jQuery, Asynchronous operations, Implementation of Fixtures and manipulation of DOM with Jasmine tests. It has vast variety of examples provided on Data driven approach, Angular JS, Node.js and CoffeeScript with Jasmine tests.Examples given in this book are to the point, overall a good book to understand and implement Jasmine tests following all good practices.
Amazon Verified review Amazon
Arun Mahendrakar Sep 11, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've read other books on Jasmine, but this one clearly has been the best. It starts out real basic defining of the Jasmine jargon-ology (I guess I just coined a new word). The first three chapters are for those who want to start out with Jasmine for the first time. TDD/BDD are described in detail in the early chapters, which helps a newbie to level-set his frame of mind on how to think in terms of writing code and unit tests.Usage of advanced concepts like working with spies, mocking AJAX, jQuery and Fixtures are divulged pretty well. The author recognizes the importance of code-coverage and dedicates an entire chapter to discuss it.As expected, the author does mention how to unit test code written using AngularJS and CoffeeScript code. The wide-range scope of Jasmine demonstrates the maturity and versatility of the testing framework.I'm hoping a future version of this book will contain a section on build automation, but this is a really great book for both beginners and experienced JavaScript developers.
Amazon Verified review Amazon
Vipul Gupta Jun 11, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I have been involved in doing evaluation of a lot of tools and frameworks to suite the day to day project and client needs. Recently did a research on "Jasmine" to validate and check it's implementation feasibility for BDD when I hit "Jasmine Cookbook".I was quite intrigued when I received this book written by Munish Sethi, as it provides practical ways how a novice can actually learn Jasmine quickly and easily. So, is it a ideal reference book for a product team to get handson on Jasmine quickly?In short: Yes. It acts as a great reference for the teams who want to implement Jasmine for their products. More importantly it acts as a quick reference for anyone who wants to begin with Jasmine.This book is divided into 9 logical chapters with each chapter focusing on a particular need that any team might be having at any particular phase of a SDLC i.e. from evaluation phase till actual implementation and measurement phase. Some of the key focus areas that the writer has brought out very clearly are1.How Jasmine can be implemented in teams following either TDD or BDD. It becomes easy for the user to understand and implement it in the projects thereafter.2.All examples relate to the real world scenarios a layman might get into, hence, makes them easy to understand3.Provides a detailed step by step approach to write your own custom "equality" and "matcher" functions in Jasmine4.Performing mocking using spyOn() method, Asynchronous operations and Implementation of Fixtures and manipulation of DOM with Jasmine tests is explained in detail.5.Includes practical usage and designing of Jasmine based automated tests to validate complex functionality developed using AJAX, jQuery, JSON Fixtures6.Apart from the automated tests, it also includes methodologies to validate the code coverage achieved through the automated tests using JavaScript Code Coverage tool Karma and Istanbul that can enable product teams to keep a check on what they are testing.Towards the end, Jasmine integration and usage with other tools like Angular JS, Node.js and CoffeeScript is touched upon. Though these could have been detailed further, but it gives a platform to quickly start in case there is a need for these technologies. But, overall the book is a great guide for a product team to take small steps to learn and implement Jasmine as per their needs.
Amazon Verified review Amazon
Dwarika Jul 16, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This book has been best design for experienced developer of JavaScript, Jquery and Ajax but presentation of content is more like a beginners guide that seems biggest USP of this book.In this book, First Three chapter are just for beginners at some extent because this section is going to help you to understand setting up Jasmine and would also teach you how to design unit tests for JavaScript and would also give you overview about matchers those gonna help you to design Jasmine Specs for pending specs along with exceptions. After going through these three chapter i am pretty sure that you would be able to differentiate the need of TDD and BDD approach . and you will get an analytical thought about the use of TDD and BDD in your project. So if you are a beginner then be happy because these three chapters are written for you and after that you would be able to understand the use of this Jasmine framework.My favorite chapter is seventh chapter that talks more about Code Coverage with Jasmine Tests, then question arises why do i like this chapter So my answer is , here you are going to generate the coverage report that is going to keep your business people satisfied and intend them to think ' all is going well <It more like slogan of 3 Idiots movie 'All iz well'>' because this shows all you effort in numbers and business people do believe in numbers and percentage. This can be achieved only after going through this chapter and from here you would be able to understand the basics of code coverage that is used in our development or automation test creation. So believe me this is the chapter that is going to bring more appreciation from your business people and senior people in company hierarchy for you. Don't worry, All the numbers and percentage of your code coverage would be taken care by the use of karma and istanbul tools. Best thing that is in this chapter is its 'How to do it' section because this is just a step by step implementation in real time project.Apart from all above what I like most is, its running code that can be either created by you while practicing this book or the same can be cloned from git repository. So after going through this book, I am pretty sure you would be pretty clear about Jasmine framework and its better use in real time environment.So at the end of this book you would be able to see one bonus chapter that is going to help you to create JavaScript App using Jasmine so this is the chapter that has been written for the pro -developers who have already master the Jasmine framework.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela