SlideShare una empresa de Scribd logo
1 de 26
Descargar para leer sin conexión
Unit Testing in JavaScript with MVC and QUnit
Lars Thorup
ZeaLake Software Consulting


June 14, 2011
Who is Lars Thorup?
●   Software developer

●   Coach: Automated testing
    and other agile practices

●   Advisor: Assesses software
    projects and companies

●   Founder and CEO of
    BestBrains and ZeaLake
Agenda
●   Sample application under test

●   How to use QUnit

●   Asynchronuous testing

●   How to use Model-View-Controller

●   Assumes knowledge about JavaScript

●   Assumes knowledge about unit testing
JavaScript must be tested in the browser
Example app: Collaborative Dialog
●   Front end entirely in JavaScript

●   Back end service methods implemented in C#
How do tests look like?
●   util.test.html

●   ok(actual, message)

●   equal(actual, expected, message)

●   same(actual, expected, message)
    ●   deep equivalence

●   raises(expected, function, message)
How to modularize tests?
●   view.test.html

●   module(name, fixture)

●   all following tests will have this being a newly created
    fixture object with setup() and teardown() run before and
    after the test
Testing ajax
●   svc.test.html

●   call expect(number-of-assertions) to verify that callbacks
    was actually called

●   call stop(timeout) before first ajax call

●   call start() when test is complete
    ●   typically inside ajax callback

●   if more than one asynchronous call in one test:
    ●   call stop() before each
    ●   call start() in callback of each
Make your JavaScript testable
●   MVC design pattern: Model - View - Controller

●   Dependency injection

●   Isolated testing                             controller




                                          view                model




                                                               svc
View
●   view.js
                                            controller
    ●   injected html
    ●   load html page from the server
    ●   html becomes directly stylable   view            model

●   Responsibilities
                                                          svc
    ●   manipulate html
    ●   generate html from templates
    ●   dispatch events to listeners
    ●   nothing more!

●   References
    ●   a set of event listeners
        (typically the controller)
Controller
●   controller.js
                                             controller

●   Responsibilities
    ●   handle all events from the
                                          view            model
        view
    ●   poll model for change events if
        relevant                                           svc
    ●   convert events to commands
        against the model
    ●   repaint strategy
    ●   error handling strategy

●   References
    ●   the model (to execute
        commands, polling)
    ●   the view (to do repainting)
Model
●   model.js
                                            controller

●   Responsibilities
    ●   cache state to minimize round
                                         view            model
        trips
    ●   provide view and controller
        with a useful interface of the                    svc
        data model

●   References
    ●   the service proxy
Service Proxy
●   svc.js
                                          controller

●   Responsibilities
    ●   provide a javascript api
                                       view            model
        mapping of the server api

●   References                                          svc
    ●   the physical server via ajax
Testing the view
●   view.test.js         test

●   Inject
    ●   controllerStub
    ●   canvas                  controllerStub

●   Invoke methods
                         view
●   Assert
    ●   canvas
    ●   controllerStub
Testing the controller
●   controller.test.js                test

●   Inject
    ●   viewStub
                                    controller
    ●   modelStub

●   Invoke methods
                         viewStub                modelStub
●   Assert
    ●   viewStub
    ●   modelStub
Testing the model
●   model.test.js     test

●   Inject
    ●   serverStub
                     model
●   Invoke methods

●   Assert
                     svcStub
    ●   state
    ●   serverStub
Testing the service proxy
●   svc.test.js             test

●   Invoke methods

●   Assert
    ●   results




                            svc
Callbacks in JavaScript
●   Ajax means asynchronous
    ●   Server methods become asynchronous
    ●   Model methods become asynchronous
    ●   To return a value you must supply a callback

●   Error handling
    ●   Include in every callback
this in JavaScript
●   Avoid using this in callbacks, since this probably refers to
    the object that invokes the callback, not the object that
    contains the code for the callback.

●   Instead use jQuery's $proxy() method
    ●   Example: controller.js
Bootstrap
●   bootstrap() function
    ●   see collabForm.js

●   creates model, view and controller and ties them together

●   start polling engine (if relevant)

●   called by onload or $(document).ready()
    ●   see Index.aspx
Run tests on build server
●   QUnit tests needs to run in a browser

●   On WIndows, the browser requires a WinStation
    ●   So the build server must be logged on at all times for this to work

●   Hard to avoid tests that hang

●   Consider running tests manually instead
Testing the backend
●   Test your webservices

●   Use QUnit and assert on the returned JSON
    ●   Or use your backend testing tool
Real World Example
●   WizerPro, in JavaScript, using MVC pattern
Further reading
●   Documentation
    ●   http://docs.jquery.com/Qunit

●   Book
    ●   "Test-Driven JavaScript Development", Christian Johansen

●   QUnit Presentation
    ●   http://benalman.com/talks/unit-testing-qunit.html
Future meetups
●   TDD coding dojo with C++ and Ruby
    ●   Thursday June 24th (in a week!)
Feedback
●   Give your evaluation at meetup.com

Más contenido relacionado

La actualidad más candente

Trusted systems1
Trusted systems1Trusted systems1
Trusted systems1Sumita Das
 
Domain Specific Languages: An introduction (DSLs)
Domain Specific Languages: An introduction (DSLs)Domain Specific Languages: An introduction (DSLs)
Domain Specific Languages: An introduction (DSLs)Pedro Silva
 
Building a Scalable Record Linkage System with Apache Spark, Python 3, and Ma...
Building a Scalable Record Linkage System with Apache Spark, Python 3, and Ma...Building a Scalable Record Linkage System with Apache Spark, Python 3, and Ma...
Building a Scalable Record Linkage System with Apache Spark, Python 3, and Ma...Databricks
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functionsmussawir20
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformationLars Marius Garshol
 
Intro to Neo4j and Graph Databases
Intro to Neo4j and Graph DatabasesIntro to Neo4j and Graph Databases
Intro to Neo4j and Graph DatabasesNeo4j
 
The DDS Tutorial - Part I
The DDS Tutorial - Part IThe DDS Tutorial - Part I
The DDS Tutorial - Part IAngelo Corsaro
 
VoltDB: as vantagens e os desafios dos banco de dados NewSQL
VoltDB: as vantagens e os desafios dos banco de dados NewSQLVoltDB: as vantagens e os desafios dos banco de dados NewSQL
VoltDB: as vantagens e os desafios dos banco de dados NewSQLLuiz Henrique Zambom Santana
 
Sv data types and sv interface usage in uvm
Sv data types and sv interface usage in uvmSv data types and sv interface usage in uvm
Sv data types and sv interface usage in uvmHARINATH REDDY
 
Top 20 FAQs on the Autonomous Database
Top 20 FAQs on the Autonomous DatabaseTop 20 FAQs on the Autonomous Database
Top 20 FAQs on the Autonomous DatabaseSandesh Rao
 
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextFind Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextCarsten Czarski
 
Machine Learning at Scale with MLflow and Apache Spark
Machine Learning at Scale with MLflow and Apache SparkMachine Learning at Scale with MLflow and Apache Spark
Machine Learning at Scale with MLflow and Apache SparkDatabricks
 
Data encryption standard DES & 3DES
Data encryption standard DES & 3DESData encryption standard DES & 3DES
Data encryption standard DES & 3DESLaís Berlatto
 
High Bandwidth Memory(HBM)
High Bandwidth Memory(HBM)High Bandwidth Memory(HBM)
High Bandwidth Memory(HBM)HARINATH REDDY
 
Transforming AI with Graphs: Real World Examples using Spark and Neo4j
Transforming AI with Graphs: Real World Examples using Spark and Neo4jTransforming AI with Graphs: Real World Examples using Spark and Neo4j
Transforming AI with Graphs: Real World Examples using Spark and Neo4jDatabricks
 

La actualidad más candente (20)

Trusted systems1
Trusted systems1Trusted systems1
Trusted systems1
 
Domain Specific Languages: An introduction (DSLs)
Domain Specific Languages: An introduction (DSLs)Domain Specific Languages: An introduction (DSLs)
Domain Specific Languages: An introduction (DSLs)
 
Building a Scalable Record Linkage System with Apache Spark, Python 3, and Ma...
Building a Scalable Record Linkage System with Apache Spark, Python 3, and Ma...Building a Scalable Record Linkage System with Apache Spark, Python 3, and Ma...
Building a Scalable Record Linkage System with Apache Spark, Python 3, and Ma...
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
Intro to Neo4j and Graph Databases
Intro to Neo4j and Graph DatabasesIntro to Neo4j and Graph Databases
Intro to Neo4j and Graph Databases
 
Blowfish Cryptosystem
Blowfish Cryptosystem Blowfish Cryptosystem
Blowfish Cryptosystem
 
The DDS Tutorial - Part I
The DDS Tutorial - Part IThe DDS Tutorial - Part I
The DDS Tutorial - Part I
 
VoltDB: as vantagens e os desafios dos banco de dados NewSQL
VoltDB: as vantagens e os desafios dos banco de dados NewSQLVoltDB: as vantagens e os desafios dos banco de dados NewSQL
VoltDB: as vantagens e os desafios dos banco de dados NewSQL
 
Two fish cipher
Two fish cipherTwo fish cipher
Two fish cipher
 
Sv data types and sv interface usage in uvm
Sv data types and sv interface usage in uvmSv data types and sv interface usage in uvm
Sv data types and sv interface usage in uvm
 
Top 20 FAQs on the Autonomous Database
Top 20 FAQs on the Autonomous DatabaseTop 20 FAQs on the Autonomous Database
Top 20 FAQs on the Autonomous Database
 
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextFind Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
 
Machine Learning at Scale with MLflow and Apache Spark
Machine Learning at Scale with MLflow and Apache SparkMachine Learning at Scale with MLflow and Apache Spark
Machine Learning at Scale with MLflow and Apache Spark
 
One-Time Pad Encryption
One-Time Pad EncryptionOne-Time Pad Encryption
One-Time Pad Encryption
 
Data encryption standard DES & 3DES
Data encryption standard DES & 3DESData encryption standard DES & 3DES
Data encryption standard DES & 3DES
 
RPC Over DDS
RPC Over DDSRPC Over DDS
RPC Over DDS
 
Introduction to RTI DDS
Introduction to RTI DDSIntroduction to RTI DDS
Introduction to RTI DDS
 
High Bandwidth Memory(HBM)
High Bandwidth Memory(HBM)High Bandwidth Memory(HBM)
High Bandwidth Memory(HBM)
 
Transforming AI with Graphs: Real World Examples using Spark and Neo4j
Transforming AI with Graphs: Real World Examples using Spark and Neo4jTransforming AI with Graphs: Real World Examples using Spark and Neo4j
Transforming AI with Graphs: Real World Examples using Spark and Neo4j
 

Destacado

Building native mobile apps using web technologies
Building native mobile apps using web technologiesBuilding native mobile apps using web technologies
Building native mobile apps using web technologiesHjörtur Hilmarsson
 
Javascript Unit Testting (PHPBenelux 2011-05-04)
Javascript Unit Testting (PHPBenelux 2011-05-04)Javascript Unit Testting (PHPBenelux 2011-05-04)
Javascript Unit Testting (PHPBenelux 2011-05-04)Tom Van Herreweghe
 
Controller Testing: You're Doing It Wrong
Controller Testing: You're Doing It WrongController Testing: You're Doing It Wrong
Controller Testing: You're Doing It Wrongjohnnygroundwork
 
Focus on the outside, testing in ASP.NET MVC
Focus on the outside, testing in ASP.NET MVCFocus on the outside, testing in ASP.NET MVC
Focus on the outside, testing in ASP.NET MVCRob Ashton
 
F# Eye for the C# Guy - DDD North 2013
F# Eye for the C# Guy - DDD North 2013F# Eye for the C# Guy - DDD North 2013
F# Eye for the C# Guy - DDD North 2013Phillip Trelford
 
ASP.NET MVC Fundamental
ASP.NET MVC FundamentalASP.NET MVC Fundamental
ASP.NET MVC Fundamentalldcphuc
 
Advanced QUnit - Front-End JavaScript Unit Testing
Advanced QUnit - Front-End JavaScript Unit TestingAdvanced QUnit - Front-End JavaScript Unit Testing
Advanced QUnit - Front-End JavaScript Unit TestingLars Thorup
 
JavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnitJavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnitTasanakorn Phaipool
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCAndy Butland
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testingjeresig
 
Laws of test automation framework
Laws of test automation frameworkLaws of test automation framework
Laws of test automation frameworkvodqancr
 
CQRS на практике. В поиске точки масштабирования и новых метафор
CQRS на практике. В поиске точки масштабирования и новых метафорCQRS на практике. В поиске точки масштабирования и новых метафор
CQRS на практике. В поиске точки масштабирования и новых метафорAlexander Byndyu
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Behavior Driven Development with Cucumber
Behavior Driven Development with CucumberBehavior Driven Development with Cucumber
Behavior Driven Development with CucumberBrandon Keepers
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScriptAutomated Web Testing using JavaScript
Automated Web Testing using JavaScriptSimon Guest
 

Destacado (20)

Building native mobile apps using web technologies
Building native mobile apps using web technologiesBuilding native mobile apps using web technologies
Building native mobile apps using web technologies
 
Javascript Unit Testting (PHPBenelux 2011-05-04)
Javascript Unit Testting (PHPBenelux 2011-05-04)Javascript Unit Testting (PHPBenelux 2011-05-04)
Javascript Unit Testting (PHPBenelux 2011-05-04)
 
Web App Mvc
Web App MvcWeb App Mvc
Web App Mvc
 
Controller Testing: You're Doing It Wrong
Controller Testing: You're Doing It WrongController Testing: You're Doing It Wrong
Controller Testing: You're Doing It Wrong
 
Focus on the outside, testing in ASP.NET MVC
Focus on the outside, testing in ASP.NET MVCFocus on the outside, testing in ASP.NET MVC
Focus on the outside, testing in ASP.NET MVC
 
F# Eye for the C# Guy - DDD North 2013
F# Eye for the C# Guy - DDD North 2013F# Eye for the C# Guy - DDD North 2013
F# Eye for the C# Guy - DDD North 2013
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
 
ASP.NET MVC Fundamental
ASP.NET MVC FundamentalASP.NET MVC Fundamental
ASP.NET MVC Fundamental
 
Advanced QUnit - Front-End JavaScript Unit Testing
Advanced QUnit - Front-End JavaScript Unit TestingAdvanced QUnit - Front-End JavaScript Unit Testing
Advanced QUnit - Front-End JavaScript Unit Testing
 
Qunit Java script Un
Qunit Java script UnQunit Java script Un
Qunit Java script Un
 
JavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnitJavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnit
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Laws of test automation framework
Laws of test automation frameworkLaws of test automation framework
Laws of test automation framework
 
CQRS на практике. В поиске точки масштабирования и новых метафор
CQRS на практике. В поиске точки масштабирования и новых метафорCQRS на практике. В поиске точки масштабирования и новых метафор
CQRS на практике. В поиске точки масштабирования и новых метафор
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
Behavior Driven Development with Cucumber
Behavior Driven Development with CucumberBehavior Driven Development with Cucumber
Behavior Driven Development with Cucumber
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScriptAutomated Web Testing using JavaScript
Automated Web Testing using JavaScript
 

Similar a Unit Testing in JavaScript with MVC and QUnit

Your journey into the serverless world
Your journey into the serverless worldYour journey into the serverless world
Your journey into the serverless worldRed Hat Developers
 
Presentation on angular 5
Presentation on angular 5Presentation on angular 5
Presentation on angular 5Ramesh Adhikari
 
Protractor End To End Testing For AngularJS
Protractor End To End Testing For AngularJSProtractor End To End Testing For AngularJS
Protractor End To End Testing For AngularJSKnoldus Inc.
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Patterngoodfriday
 
Spine js & creating non blocking user interfaces
Spine js & creating non blocking user interfacesSpine js & creating non blocking user interfaces
Spine js & creating non blocking user interfacesHjörtur Hilmarsson
 
Asp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design PatternAsp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design Patternmaddinapudi
 
Design & Development of Web Applications using SpringMVC
Design & Development of Web Applications using SpringMVC Design & Development of Web Applications using SpringMVC
Design & Development of Web Applications using SpringMVC Naresh Chintalcheru
 
Hanselman lipton asp_connections_ams304_mvc
Hanselman lipton asp_connections_ams304_mvcHanselman lipton asp_connections_ams304_mvc
Hanselman lipton asp_connections_ams304_mvcdenemedeniz
 
Gwt session
Gwt sessionGwt session
Gwt sessionMans Jug
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Lars Thorup
 
Testing Tools Online Training.pdf
Testing Tools Online Training.pdfTesting Tools Online Training.pdf
Testing Tools Online Training.pdfSpiritsoftsTraining
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIVisual Engineering
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introductionOndrej Mihályi
 
Salesforce Developer Online Training.pdf
Salesforce Developer Online Training.pdfSalesforce Developer Online Training.pdf
Salesforce Developer Online Training.pdfSpiritsoftsTraining
 
[Scrum Breakfast DN] Is it possible to make 100% Unit Test coverage for your ...
[Scrum Breakfast DN] Is it possible to make 100% Unit Test coverage for your ...[Scrum Breakfast DN] Is it possible to make 100% Unit Test coverage for your ...
[Scrum Breakfast DN] Is it possible to make 100% Unit Test coverage for your ...Scrum Breakfast Vietnam
 

Similar a Unit Testing in JavaScript with MVC and QUnit (20)

Your journey into the serverless world
Your journey into the serverless worldYour journey into the serverless world
Your journey into the serverless world
 
Presentation on angular 5
Presentation on angular 5Presentation on angular 5
Presentation on angular 5
 
Protractor End To End Testing For AngularJS
Protractor End To End Testing For AngularJSProtractor End To End Testing For AngularJS
Protractor End To End Testing For AngularJS
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
 
Spine js & creating non blocking user interfaces
Spine js & creating non blocking user interfacesSpine js & creating non blocking user interfaces
Spine js & creating non blocking user interfaces
 
Asp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design PatternAsp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design Pattern
 
Design & Development of Web Applications using SpringMVC
Design & Development of Web Applications using SpringMVC Design & Development of Web Applications using SpringMVC
Design & Development of Web Applications using SpringMVC
 
Hanselman lipton asp_connections_ams304_mvc
Hanselman lipton asp_connections_ams304_mvcHanselman lipton asp_connections_ams304_mvc
Hanselman lipton asp_connections_ams304_mvc
 
ASP.NET MVC 3
ASP.NET MVC 3ASP.NET MVC 3
ASP.NET MVC 3
 
Angular js
Angular jsAngular js
Angular js
 
AngularJS Workshop
AngularJS WorkshopAngularJS Workshop
AngularJS Workshop
 
Gwt session
Gwt sessionGwt session
Gwt session
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
 
Testing Tools Online Training.pdf
Testing Tools Online Training.pdfTesting Tools Online Training.pdf
Testing Tools Online Training.pdf
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte III
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introduction
 
Gwt session
Gwt sessionGwt session
Gwt session
 
QSpiders - Simple Recording and Configuration of recording options for HP Loa...
QSpiders - Simple Recording and Configuration of recording options for HP Loa...QSpiders - Simple Recording and Configuration of recording options for HP Loa...
QSpiders - Simple Recording and Configuration of recording options for HP Loa...
 
Salesforce Developer Online Training.pdf
Salesforce Developer Online Training.pdfSalesforce Developer Online Training.pdf
Salesforce Developer Online Training.pdf
 
[Scrum Breakfast DN] Is it possible to make 100% Unit Test coverage for your ...
[Scrum Breakfast DN] Is it possible to make 100% Unit Test coverage for your ...[Scrum Breakfast DN] Is it possible to make 100% Unit Test coverage for your ...
[Scrum Breakfast DN] Is it possible to make 100% Unit Test coverage for your ...
 

Más de Lars Thorup

100 tests per second - 40 releases per week
100 tests per second - 40 releases per week100 tests per second - 40 releases per week
100 tests per second - 40 releases per weekLars Thorup
 
SQL or NoSQL - how to choose
SQL or NoSQL - how to chooseSQL or NoSQL - how to choose
SQL or NoSQL - how to chooseLars Thorup
 
Super fast end-to-end-tests
Super fast end-to-end-testsSuper fast end-to-end-tests
Super fast end-to-end-testsLars Thorup
 
Extreme Programming - to the next-level
Extreme Programming - to the next-levelExtreme Programming - to the next-level
Extreme Programming - to the next-levelLars Thorup
 
Advanced Javascript Unit Testing
Advanced Javascript Unit TestingAdvanced Javascript Unit Testing
Advanced Javascript Unit TestingLars Thorup
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy codeLars Thorup
 
Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"Lars Thorup
 
Database Schema Evolution
Database Schema EvolutionDatabase Schema Evolution
Database Schema EvolutionLars Thorup
 
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 TestingLars Thorup
 
Javascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and SinonJavascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and SinonLars Thorup
 
Continuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScriptContinuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScriptLars Thorup
 
Automated Performance Testing
Automated Performance TestingAutomated Performance Testing
Automated Performance TestingLars Thorup
 
High Performance Software Engineering Teams
High Performance Software Engineering TeamsHigh Performance Software Engineering Teams
High Performance Software Engineering TeamsLars Thorup
 
Elephant Carpaccio
Elephant CarpaccioElephant Carpaccio
Elephant CarpaccioLars Thorup
 
Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++Lars Thorup
 
Introduction to Automated Testing
Introduction to Automated TestingIntroduction to Automated Testing
Introduction to Automated TestingLars Thorup
 

Más de Lars Thorup (17)

100 tests per second - 40 releases per week
100 tests per second - 40 releases per week100 tests per second - 40 releases per week
100 tests per second - 40 releases per week
 
SQL or NoSQL - how to choose
SQL or NoSQL - how to chooseSQL or NoSQL - how to choose
SQL or NoSQL - how to choose
 
Super fast end-to-end-tests
Super fast end-to-end-testsSuper fast end-to-end-tests
Super fast end-to-end-tests
 
Extreme Programming - to the next-level
Extreme Programming - to the next-levelExtreme Programming - to the next-level
Extreme Programming - to the next-level
 
Advanced Javascript Unit Testing
Advanced Javascript Unit TestingAdvanced Javascript Unit Testing
Advanced Javascript Unit Testing
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
 
Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"
 
Database Schema Evolution
Database Schema EvolutionDatabase Schema Evolution
Database Schema Evolution
 
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
 
Javascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and SinonJavascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and Sinon
 
Continuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScriptContinuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScript
 
Automated Performance Testing
Automated Performance TestingAutomated Performance Testing
Automated Performance Testing
 
Agile Contracts
Agile ContractsAgile Contracts
Agile Contracts
 
High Performance Software Engineering Teams
High Performance Software Engineering TeamsHigh Performance Software Engineering Teams
High Performance Software Engineering Teams
 
Elephant Carpaccio
Elephant CarpaccioElephant Carpaccio
Elephant Carpaccio
 
Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++
 
Introduction to Automated Testing
Introduction to Automated TestingIntroduction to Automated Testing
Introduction to Automated Testing
 

Último

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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...Martijn de Jong
 
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)wesley chun
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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 productivityPrincipled Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
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 DevelopmentsTrustArc
 

Último (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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...
 
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)
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 

Unit Testing in JavaScript with MVC and QUnit

  • 1. Unit Testing in JavaScript with MVC and QUnit Lars Thorup ZeaLake Software Consulting June 14, 2011
  • 2. Who is Lars Thorup? ● Software developer ● Coach: Automated testing and other agile practices ● Advisor: Assesses software projects and companies ● Founder and CEO of BestBrains and ZeaLake
  • 3. Agenda ● Sample application under test ● How to use QUnit ● Asynchronuous testing ● How to use Model-View-Controller ● Assumes knowledge about JavaScript ● Assumes knowledge about unit testing
  • 4. JavaScript must be tested in the browser
  • 5. Example app: Collaborative Dialog ● Front end entirely in JavaScript ● Back end service methods implemented in C#
  • 6. How do tests look like? ● util.test.html ● ok(actual, message) ● equal(actual, expected, message) ● same(actual, expected, message) ● deep equivalence ● raises(expected, function, message)
  • 7. How to modularize tests? ● view.test.html ● module(name, fixture) ● all following tests will have this being a newly created fixture object with setup() and teardown() run before and after the test
  • 8. Testing ajax ● svc.test.html ● call expect(number-of-assertions) to verify that callbacks was actually called ● call stop(timeout) before first ajax call ● call start() when test is complete ● typically inside ajax callback ● if more than one asynchronous call in one test: ● call stop() before each ● call start() in callback of each
  • 9. Make your JavaScript testable ● MVC design pattern: Model - View - Controller ● Dependency injection ● Isolated testing controller view model svc
  • 10. View ● view.js controller ● injected html ● load html page from the server ● html becomes directly stylable view model ● Responsibilities svc ● manipulate html ● generate html from templates ● dispatch events to listeners ● nothing more! ● References ● a set of event listeners (typically the controller)
  • 11. Controller ● controller.js controller ● Responsibilities ● handle all events from the view model view ● poll model for change events if relevant svc ● convert events to commands against the model ● repaint strategy ● error handling strategy ● References ● the model (to execute commands, polling) ● the view (to do repainting)
  • 12. Model ● model.js controller ● Responsibilities ● cache state to minimize round view model trips ● provide view and controller with a useful interface of the svc data model ● References ● the service proxy
  • 13. Service Proxy ● svc.js controller ● Responsibilities ● provide a javascript api view model mapping of the server api ● References svc ● the physical server via ajax
  • 14. Testing the view ● view.test.js test ● Inject ● controllerStub ● canvas controllerStub ● Invoke methods view ● Assert ● canvas ● controllerStub
  • 15. Testing the controller ● controller.test.js test ● Inject ● viewStub controller ● modelStub ● Invoke methods viewStub modelStub ● Assert ● viewStub ● modelStub
  • 16. Testing the model ● model.test.js test ● Inject ● serverStub model ● Invoke methods ● Assert svcStub ● state ● serverStub
  • 17. Testing the service proxy ● svc.test.js test ● Invoke methods ● Assert ● results svc
  • 18. Callbacks in JavaScript ● Ajax means asynchronous ● Server methods become asynchronous ● Model methods become asynchronous ● To return a value you must supply a callback ● Error handling ● Include in every callback
  • 19. this in JavaScript ● Avoid using this in callbacks, since this probably refers to the object that invokes the callback, not the object that contains the code for the callback. ● Instead use jQuery's $proxy() method ● Example: controller.js
  • 20. Bootstrap ● bootstrap() function ● see collabForm.js ● creates model, view and controller and ties them together ● start polling engine (if relevant) ● called by onload or $(document).ready() ● see Index.aspx
  • 21. Run tests on build server ● QUnit tests needs to run in a browser ● On WIndows, the browser requires a WinStation ● So the build server must be logged on at all times for this to work ● Hard to avoid tests that hang ● Consider running tests manually instead
  • 22. Testing the backend ● Test your webservices ● Use QUnit and assert on the returned JSON ● Or use your backend testing tool
  • 23. Real World Example ● WizerPro, in JavaScript, using MVC pattern
  • 24. Further reading ● Documentation ● http://docs.jquery.com/Qunit ● Book ● "Test-Driven JavaScript Development", Christian Johansen ● QUnit Presentation ● http://benalman.com/talks/unit-testing-qunit.html
  • 25. Future meetups ● TDD coding dojo with C++ and Ruby ● Thursday June 24th (in a week!)
  • 26. Feedback ● Give your evaluation at meetup.com