SlideShare a Scribd company logo
1 of 14
Download to read offline
Testing your Javascript with
              Jasmine
   Getting the fun of BDD into JS
What is Jasmine?
   Jasmine is a behavior driven development
    framework to test your javascript code. With a
    sintax similar to that of Rspec, Jasmine can
    help us to ensure our Javascript is well
    integrated across our site.
spec-diff
   describe Admin::UsersController do        describe("checkBoxesEnhanced", function() {
    fixtures :users                           beforeEach(function() {
                                                 ...

                                                });
    before(:each) do                           describe("clicking the master checkbox", function(){
                                                  it("should be able to check all product attributes
     @users = User.make                      checkboxes when checked", function() {
                                                    checkAll.attr('checked', true);
    end                                            checkAll.click();
                                                    expect(controlled.attr('checked')).toBe(true);
                                                 });
                                                 ...
    describe "GET 'index'" do                   ...
                                                });
     ...                                     });

     it "is successful" do

       get :index

       response.should be_success

     end

    end
The master-slave checkbox
             problem
   For one of the developments we have @
    crowdint, we had a task that involved a
    master checkbox controlling a set of slave
    checkboxes and viceversa. The following
    were the requirements:
The master-slave checkbox
             problem
   When clicking the master checkbox:
   - When checked, all the slave checkboxes
    should be checked and should remove the
    "partially-selected" class if present.
   - When unchecked, all the slave checkboxes
    should be unchecked and should remove the
    "partially-selected" class if present.
The master-slave checkbox
              problem
   When clicking the slave checkboxes:
   -When all of the slave checkboxes are checked, the master checkbox
    should be checked, and remove the "partially-selected" class if present.
   -When all of the slave checkboxes are unchecked, the master checkbox
    should be unchecked, and remove the "partially-selected" class if
    present.
   -When some of the slave boxes are checked and some other are
    unchecked, the master checkbox should be unchecked and have a
    "partially-selected" class.
Installing Jasmine
   Add gem "jasmine" to your Gemfile
   Bundle install
   Go to the spec directory in your rails app and do jasmine init
   Next, run “rake jasmine”




   Now you should be able to goto: http://localhost:8888 and you will have 2
    tests run.
The spec file
   So, in order to create my specs, I have to create a file under
    the directory spec/javascrips (remember we called the
    jasmine init command at that level), so I will create
    MasterSlaveCheckbox.js over there



   spec/javascripts/MasterSlaveCheckbox.js
   Next time we reload the localhost:8888, it will check this file
    for "it" blocks and will show them.
JS Source files
   So, we may have created our specs, but don't rush, because
    Jasmine is not like rspec and will not try to find a similar file
    name without the spec suffix. In order to see the source files,
    Jasmine needs you to include them in a special file
   spec/javascripts/support/jasmine.yml
   So , in this file include the following line under src_files:
   -public/javascripts/MasterSlaveChecbox.js
   and create your source file with the path specified above.
Coding our tests
   Let us begin with one of our requirements:
   When clicking the master checkbox:
   - When checked, all the slave checkboxes
    should be checked.
Coding our tests
   describe("MasterSlaveCheckbox", function{
    describe("when clicking on the master checkbox",function{
     it("should check all slave checkboxes when checked", function(){
          slaves.attr("checked", false);
          master.attr("checked", true);
          master.click();
          expect(slaves.attr("checked")).toBeTruthy();
     });
    });
   });
Setting up our DOM
   describe("checkBoxesEnhanced", function() {
    beforeEach(function() {
       elements = $("<input type= "checkbox" id="master"><input
    type= "checkbox" class="slave"><input type= "checkbox" class="slave">");
          $("body").append(elements);
          master = $("#master");
          slaves = $(".slave");
          slave1 = controlled.first();
          slave2 = controlled.last();
    checkOrUncheckBoxesWithBox(master, slaves);
    });
The "real" code
   function checkOrUncheckBoxesWithBox(master, slaves){
           master.click(function(){
            slaves.attr("checked", $(this).attr("checked"));
            removeClassIfPresent(master, "partially-checked");
           });
   });




   function removeClassIfPresent(e,klass){
       if(e.hasClass(klass)){
           e.removeClass(klass);
       }
   }
Contact




@planitiaboreali



Ignacio.delamadrid@crowdint.com

More Related Content

What's hot

Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Say Hello To Ecmascript 5
Say Hello To Ecmascript 5
Juriy Zaytsev
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
Josh Mock
 
Scala ActiveRecord
Scala ActiveRecordScala ActiveRecord
Scala ActiveRecord
scalaconfjp
 

What's hot (20)

Why ruby
Why rubyWhy ruby
Why ruby
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mocha
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Say Hello To Ecmascript 5
Say Hello To Ecmascript 5
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with Jasmine
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn Ruby
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Unit Testing Express Middleware
Unit Testing Express MiddlewareUnit Testing Express Middleware
Unit Testing Express Middleware
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
 
Testing JavaScript Applications
Testing JavaScript ApplicationsTesting JavaScript Applications
Testing JavaScript Applications
 
Scala ActiveRecord
Scala ActiveRecordScala ActiveRecord
Scala ActiveRecord
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 

Similar to Testing your javascript code with jasmine

An Introduction to AngularJs Unittesting
An Introduction to AngularJs UnittestingAn Introduction to AngularJs Unittesting
An Introduction to AngularJs Unittesting
Inthra onsap
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
Andy Peterson
 

Similar to Testing your javascript code with jasmine (20)

Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to Protractor
 
An Introduction to AngularJs Unittesting
An Introduction to AngularJs UnittestingAn Introduction to AngularJs Unittesting
An Introduction to AngularJs Unittesting
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
The Scalactic Way
The Scalactic WayThe Scalactic Way
The Scalactic Way
 
Barcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationBarcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentation
 
jasmine
jasminejasmine
jasmine
 
Tom Lazar Using Zope3 Views And Viewlets For Plone 3.0 Product Development
Tom Lazar   Using Zope3 Views And Viewlets For Plone 3.0 Product DevelopmentTom Lazar   Using Zope3 Views And Viewlets For Plone 3.0 Product Development
Tom Lazar Using Zope3 Views And Viewlets For Plone 3.0 Product Development
 
How do I write testable javascript?
How do I write testable javascript?How do I write testable javascript?
How do I write testable javascript?
 
How do I write Testable Javascript
How do I write Testable JavascriptHow do I write Testable Javascript
How do I write Testable Javascript
 
How do I write Testable Javascript?
How do I write Testable Javascript?How do I write Testable Javascript?
How do I write Testable Javascript?
 
Vuejs testing
Vuejs testingVuejs testing
Vuejs testing
 
G*ワークショップ in 仙台 Grails(とことん)入門
G*ワークショップ in 仙台 Grails(とことん)入門G*ワークショップ in 仙台 Grails(とことん)入門
G*ワークショップ in 仙台 Grails(とことん)入門
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasmine
 
Specs2
Specs2Specs2
Specs2
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
Creating Gradle Plugins - Oredev
Creating Gradle Plugins - OredevCreating Gradle Plugins - Oredev
Creating Gradle Plugins - Oredev
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Testing your javascript code with jasmine

  • 1. Testing your Javascript with Jasmine  Getting the fun of BDD into JS
  • 2. What is Jasmine?  Jasmine is a behavior driven development framework to test your javascript code. With a sintax similar to that of Rspec, Jasmine can help us to ensure our Javascript is well integrated across our site.
  • 3. spec-diff  describe Admin::UsersController do describe("checkBoxesEnhanced", function() {  fixtures :users beforeEach(function() { ...  });  before(:each) do describe("clicking the master checkbox", function(){ it("should be able to check all product attributes  @users = User.make checkboxes when checked", function() { checkAll.attr('checked', true);  end checkAll.click(); expect(controlled.attr('checked')).toBe(true);  }); ...  describe "GET 'index'" do ... });  ... });  it "is successful" do  get :index  response.should be_success  end  end
  • 4. The master-slave checkbox problem  For one of the developments we have @ crowdint, we had a task that involved a master checkbox controlling a set of slave checkboxes and viceversa. The following were the requirements:
  • 5. The master-slave checkbox problem  When clicking the master checkbox:  - When checked, all the slave checkboxes should be checked and should remove the "partially-selected" class if present.  - When unchecked, all the slave checkboxes should be unchecked and should remove the "partially-selected" class if present.
  • 6. The master-slave checkbox problem  When clicking the slave checkboxes:  -When all of the slave checkboxes are checked, the master checkbox should be checked, and remove the "partially-selected" class if present.  -When all of the slave checkboxes are unchecked, the master checkbox should be unchecked, and remove the "partially-selected" class if present.  -When some of the slave boxes are checked and some other are unchecked, the master checkbox should be unchecked and have a "partially-selected" class.
  • 7. Installing Jasmine  Add gem "jasmine" to your Gemfile  Bundle install  Go to the spec directory in your rails app and do jasmine init  Next, run “rake jasmine”   Now you should be able to goto: http://localhost:8888 and you will have 2 tests run.
  • 8. The spec file  So, in order to create my specs, I have to create a file under the directory spec/javascrips (remember we called the jasmine init command at that level), so I will create MasterSlaveCheckbox.js over there   spec/javascripts/MasterSlaveCheckbox.js  Next time we reload the localhost:8888, it will check this file for "it" blocks and will show them.
  • 9. JS Source files  So, we may have created our specs, but don't rush, because Jasmine is not like rspec and will not try to find a similar file name without the spec suffix. In order to see the source files, Jasmine needs you to include them in a special file  spec/javascripts/support/jasmine.yml  So , in this file include the following line under src_files:  -public/javascripts/MasterSlaveChecbox.js  and create your source file with the path specified above.
  • 10. Coding our tests  Let us begin with one of our requirements:  When clicking the master checkbox:  - When checked, all the slave checkboxes should be checked.
  • 11. Coding our tests  describe("MasterSlaveCheckbox", function{  describe("when clicking on the master checkbox",function{  it("should check all slave checkboxes when checked", function(){  slaves.attr("checked", false);  master.attr("checked", true);  master.click();  expect(slaves.attr("checked")).toBeTruthy();  });  });  });
  • 12. Setting up our DOM  describe("checkBoxesEnhanced", function() {  beforeEach(function() {  elements = $("<input type= "checkbox" id="master"><input type= "checkbox" class="slave"><input type= "checkbox" class="slave">");  $("body").append(elements);  master = $("#master");  slaves = $(".slave");  slave1 = controlled.first();  slave2 = controlled.last();  checkOrUncheckBoxesWithBox(master, slaves);  });
  • 13. The "real" code  function checkOrUncheckBoxesWithBox(master, slaves){  master.click(function(){  slaves.attr("checked", $(this).attr("checked"));  removeClassIfPresent(master, "partially-checked");  });  });   function removeClassIfPresent(e,klass){  if(e.hasClass(klass)){  e.removeClass(klass);  }  }