SlideShare une entreprise Scribd logo
1  sur  15
Télécharger pour lire hors ligne
Testing with Jasmine
 http://pivotal.github.com/jasmine/
Me

http://twitter.com/secoif
https://plus.google.com/114792856033491742337

Working at netengine
http://www.netengine.com.au

Looking for cool side-projects
Unit Test Structure – Specs

Named test functions

it('should increment a variable', function () {
  var foo = 0;           // set up the world
  foo++;                // call your application code
  expect(foo).toEqual(1); // passes because foo == 1
});
Unit Test Structure – Suites

Collections of specs
Your test files will contain one or more suites, each with one or
more specs.

describe("User Validation", function() {
   it("requires a name", function() {
      //spec content
   })
   it("does not validate invalid names", function() {
      //spec content
   })
});
Unit Test Structure – expect()

expect() is the actual 'test'
Takes a value, then 'matchers'


it('should increment a variable', function () {
  var foo = 0;           // set up the world
  foo++;                // call your application code
  expect(foo).toEqual(1); // passes because foo == 1
});
Matchers
Running Jasmine Tests
<!DOCTYPE html>
<html>
<head>
 <title>Jasmine Test Runner</title>

 <!-- Jasmine Library -->
 <link rel="stylesheet" type="text/css" href="/lib/jasmine.css">
 <script type="text/javascript" src="/lib/jasmine.js"></script>
 <script type="text/javascript" src="/lib/jasmine.html.js"></script>

 <!-- App Dependencies -->
 <script src="/public/scripts/application.js" type="text/javascript" charset="utf-8"></script>
 <script src="/public/scripts/lib/jquery.js" type="text/javascript" charset="utf-8"></script>

 <!-- Specs -->
 <script src="/specs/User.spec.js" type="text/javascript" charset="utf-8"></script>

</head>
<body>

 <script type="text/javascript">
  jasmine.getEnv().addReporter(new jasmine.TrivialReporter());
  jasmine.getEnv().execute();
 </script>
</body>
</html>
Running Jasmine Tests

Use a simple http server to serve the content
  eg python -m SimpleHTTPServer
Point browser at jasmine location
Using Jasmine to test Views

Include 'jasmine.html.js' & jquery (or whatever)
<script type="text/javascript" src="/lib/mock-ajax.js"></script>
<script type="text/javascript" src="/lib/spec-helper.js"></script>

Create dom fixtures with $('<div>HTML HERE</div>')
Test using jquery/js statements

  var dom = $('<div class="container"/>')
  sixfourty-by-foureighty-izer($('.container', dom))
  expect($('.container', dom).width()).toBe(640)
  expect($('.container', dom).height()).toBe(480)
Mocking in Jasmine

A test is not a unit test if:

 1. It talks to the database
 2. It communicates across the network
 3. It touches the file system
 4. It can't run correctly at the same time as any of your other unit
    tests
 5. You have to do special things to your environment (such as
    editing config files) to run it.
~ Michael Feathers

Need to use mocks to simulate calls to external services, files, etc
Need to use mocks to reduce real dependencies in tests.
Mocking in Jasmine – Spies

Easily inject mock/monitoring objects
Replaces or wraps the function it's spying on
Gives run-time statistics on the spied function
 ● Know how many times a function has been called
 ● Inspect return values
 ● Inspect parameters
 ● etc

it "can detect a click", ->
   spyOn(clickDetector, 'addClickStatus').andCallThrough()
   expect($('.statusList .status.clicked', dom).size()).toBe(0)
   $('.sensor', dom).click()
   expect($('.statusList .status.clicked', dom).size()).toBe(1)
   expect(clickDetector.addClickStatus).toHaveBeenCalled()
Spies
Using Jasmine to test ajax calls

Use jasmine-ajax to create fake ajax requests/responses https:
//github.com/pivotal/jasmine-ajax

Possibly get better support for ajax mocking and spying via
http://sinonjs.org/

Demo source has an example.

Perhaps next meetup.
Jasmine Examples

Demo source
https://github.com/secoif/Jasmine-Demo-Thing

Javascript Koans (DO THE KOANS)
https://github.com/liammclennan/JavaScript-Koans

Spine.js Source
https://github.com/maccman/spine/tree/master/test/specs

Awesome 3 part tutorial testing with Jasmine, Sinon and
Backbone
http://tinnedfruit.com/2011/03/03/testing-backbone-apps-with-
jasmine-sinon.html
Thanks.

Questions?

Contenu connexe

Tendances

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
 

Tendances (20)

Jasmine BDD for Javascript
Jasmine BDD for JavascriptJasmine BDD for Javascript
Jasmine BDD for Javascript
 
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...
 
Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma intro
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJS
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
 
AngularJS Unit Testing
AngularJS Unit TestingAngularJS Unit Testing
AngularJS Unit Testing
 
Angular testing
Angular testingAngular testing
Angular testing
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101
 
Karma - JS Test Runner
Karma - JS Test RunnerKarma - JS Test Runner
Karma - JS Test Runner
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
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
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Angular JS Unit Testing - Overview
Angular JS Unit Testing - OverviewAngular JS Unit Testing - Overview
Angular JS Unit Testing - Overview
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mocha
 
Unit Testing Express Middleware
Unit Testing Express MiddlewareUnit Testing Express Middleware
Unit Testing Express Middleware
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to Protractor
 

Similaire à Intro to testing Javascript with jasmine

Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Lohika_Odessa_TechTalks
 
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
 

Similaire à Intro to testing Javascript with jasmine (20)

Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
 
Nashville Symfony Functional Testing
Nashville Symfony Functional TestingNashville Symfony Functional Testing
Nashville Symfony Functional Testing
 
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
 
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
 
Web UI test automation instruments
Web UI test automation instrumentsWeb UI test automation instruments
Web UI test automation instruments
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
 
Building frameworks over Selenium
Building frameworks over SeleniumBuilding frameworks over Selenium
Building frameworks over Selenium
 
Getting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingGetting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe Testing
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven framework
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to Deployment
 
Painless Javascript Unit Testing
Painless Javascript Unit TestingPainless Javascript Unit Testing
Painless Javascript Unit Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
 
Better Testing With PHP Unit
Better Testing With PHP UnitBetter Testing With PHP Unit
Better Testing With PHP Unit
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 

Plus de Timothy Oxley (6)

Modular vs Monolith
Modular vs MonolithModular vs Monolith
Modular vs Monolith
 
Components vs Frameworks
Components vs FrameworksComponents vs Frameworks
Components vs Frameworks
 
Bundling Client Side Assets
Bundling Client Side AssetsBundling Client Side Assets
Bundling Client Side Assets
 
component: ruby gems for the browser
component: ruby gems for the browsercomponent: ruby gems for the browser
component: ruby gems for the browser
 
Benefits of Clientside templating for Red Dot Ruby
Benefits of Clientside templating for Red Dot RubyBenefits of Clientside templating for Red Dot Ruby
Benefits of Clientside templating for Red Dot Ruby
 
Testable client side_mvc_apps_in_javascript
Testable client side_mvc_apps_in_javascriptTestable client side_mvc_apps_in_javascript
Testable client side_mvc_apps_in_javascript
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 
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
 
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
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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
 
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, ...
 
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)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 

Intro to testing Javascript with jasmine

  • 1. Testing with Jasmine http://pivotal.github.com/jasmine/
  • 3. Unit Test Structure – Specs Named test functions it('should increment a variable', function () { var foo = 0; // set up the world foo++; // call your application code expect(foo).toEqual(1); // passes because foo == 1 });
  • 4. Unit Test Structure – Suites Collections of specs Your test files will contain one or more suites, each with one or more specs. describe("User Validation", function() { it("requires a name", function() { //spec content }) it("does not validate invalid names", function() { //spec content }) });
  • 5. Unit Test Structure – expect() expect() is the actual 'test' Takes a value, then 'matchers' it('should increment a variable', function () { var foo = 0; // set up the world foo++; // call your application code expect(foo).toEqual(1); // passes because foo == 1 });
  • 7. Running Jasmine Tests <!DOCTYPE html> <html> <head> <title>Jasmine Test Runner</title> <!-- Jasmine Library --> <link rel="stylesheet" type="text/css" href="/lib/jasmine.css"> <script type="text/javascript" src="/lib/jasmine.js"></script> <script type="text/javascript" src="/lib/jasmine.html.js"></script> <!-- App Dependencies --> <script src="/public/scripts/application.js" type="text/javascript" charset="utf-8"></script> <script src="/public/scripts/lib/jquery.js" type="text/javascript" charset="utf-8"></script> <!-- Specs --> <script src="/specs/User.spec.js" type="text/javascript" charset="utf-8"></script> </head> <body> <script type="text/javascript"> jasmine.getEnv().addReporter(new jasmine.TrivialReporter()); jasmine.getEnv().execute(); </script> </body> </html>
  • 8. Running Jasmine Tests Use a simple http server to serve the content eg python -m SimpleHTTPServer Point browser at jasmine location
  • 9. Using Jasmine to test Views Include 'jasmine.html.js' & jquery (or whatever) <script type="text/javascript" src="/lib/mock-ajax.js"></script> <script type="text/javascript" src="/lib/spec-helper.js"></script> Create dom fixtures with $('<div>HTML HERE</div>') Test using jquery/js statements var dom = $('<div class="container"/>') sixfourty-by-foureighty-izer($('.container', dom)) expect($('.container', dom).width()).toBe(640) expect($('.container', dom).height()).toBe(480)
  • 10. Mocking in Jasmine A test is not a unit test if: 1. It talks to the database 2. It communicates across the network 3. It touches the file system 4. It can't run correctly at the same time as any of your other unit tests 5. You have to do special things to your environment (such as editing config files) to run it. ~ Michael Feathers Need to use mocks to simulate calls to external services, files, etc Need to use mocks to reduce real dependencies in tests.
  • 11. Mocking in Jasmine – Spies Easily inject mock/monitoring objects Replaces or wraps the function it's spying on Gives run-time statistics on the spied function ● Know how many times a function has been called ● Inspect return values ● Inspect parameters ● etc it "can detect a click", -> spyOn(clickDetector, 'addClickStatus').andCallThrough() expect($('.statusList .status.clicked', dom).size()).toBe(0) $('.sensor', dom).click() expect($('.statusList .status.clicked', dom).size()).toBe(1) expect(clickDetector.addClickStatus).toHaveBeenCalled()
  • 12. Spies
  • 13. Using Jasmine to test ajax calls Use jasmine-ajax to create fake ajax requests/responses https: //github.com/pivotal/jasmine-ajax Possibly get better support for ajax mocking and spying via http://sinonjs.org/ Demo source has an example. Perhaps next meetup.
  • 14. Jasmine Examples Demo source https://github.com/secoif/Jasmine-Demo-Thing Javascript Koans (DO THE KOANS) https://github.com/liammclennan/JavaScript-Koans Spine.js Source https://github.com/maccman/spine/tree/master/test/specs Awesome 3 part tutorial testing with Jasmine, Sinon and Backbone http://tinnedfruit.com/2011/03/03/testing-backbone-apps-with- jasmine-sinon.html