Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Jasmine Cookbook

You're reading from   Jasmine Cookbook Over 35 recipes to design and develop Jasmine tests to produce world-class JavaScript applications

Arrow left icon
Product type Paperback
Published in Apr 2015
Publisher
ISBN-13 9781784397166
Length 276 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Munish Kumar Munish Kumar
Author Profile Icon Munish Kumar
Munish Kumar
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

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

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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image