SlideShare a Scribd company logo
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
Ad

Recommended

Maven Introduction
Maven Introduction
Sandeep Chawla
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask
Hoang Ngo
 
Building native mobile apps using web technologies
Building native mobile apps using web technologies
Hjörtur Hilmarsson
 
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 Wrong
johnnygroundwork
 
Focus on the outside, testing in ASP.NET MVC
Focus on the outside, testing in ASP.NET MVC
Rob Ashton
 
F# Eye for the C# Guy - DDD North 2013
F# Eye for the C# Guy - DDD North 2013
Phillip Trelford
 
JavaScript Unit Testing
JavaScript Unit Testing
Christian Johansen
 
ASP.NET MVC Fundamental
ASP.NET MVC Fundamental
ldcphuc
 
Advanced QUnit - Front-End JavaScript Unit Testing
Advanced QUnit - Front-End JavaScript Unit Testing
Lars Thorup
 
Qunit Java script Un
Qunit Java script Un
akanksha arora
 
JavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnit
Tasanakorn Phaipool
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
Andy Butland
 
Understanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 
Laws of test automation framework
Laws of test automation framework
vodqancr
 
CQRS на практике. В поиске точки масштабирования и новых метафор
CQRS на практике. В поиске точки масштабирования и новых метафор
Alexander Byndyu
 
Unit and integration Testing
Unit and integration Testing
David Berliner
 
Model View Controller (MVC)
Model View Controller (MVC)
Javier Antonio Humarán Peñuñuri
 
Mvc architecture
Mvc architecture
Surbhi Panhalkar
 
Behavior Driven Development with Cucumber
Behavior Driven Development with Cucumber
Brandon Keepers
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScript
Simon Guest
 
Viking academy backbone.js
Viking academy backbone.js
Bert Wijnants
 
Javascript for Wep Apps
Javascript for Wep Apps
Michael Puckett
 
Introduction to Knockoutjs
Introduction to Knockoutjs
jhoguet
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!
Roberto Messora
 
MVC pattern for widgets
MVC pattern for widgets
Behnam Taraghi
 
Give your web apps some backbone
Give your web apps some backbone
RTigger
 
Clean Javascript
Clean Javascript
Ryunosuke SATO
 
Planbox Backbone MVC
Planbox Backbone MVC
Acquisio
 

More Related Content

Viewers also liked (14)

JavaScript Unit Testing
JavaScript Unit Testing
Christian Johansen
 
ASP.NET MVC Fundamental
ASP.NET MVC Fundamental
ldcphuc
 
Advanced QUnit - Front-End JavaScript Unit Testing
Advanced QUnit - Front-End JavaScript Unit Testing
Lars Thorup
 
Qunit Java script Un
Qunit Java script Un
akanksha arora
 
JavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnit
Tasanakorn Phaipool
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
Andy Butland
 
Understanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 
Laws of test automation framework
Laws of test automation framework
vodqancr
 
CQRS на практике. В поиске точки масштабирования и новых метафор
CQRS на практике. В поиске точки масштабирования и новых метафор
Alexander Byndyu
 
Unit and integration Testing
Unit and integration Testing
David Berliner
 
Model View Controller (MVC)
Model View Controller (MVC)
Javier Antonio Humarán Peñuñuri
 
Mvc architecture
Mvc architecture
Surbhi Panhalkar
 
Behavior Driven Development with Cucumber
Behavior Driven Development with Cucumber
Brandon Keepers
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScript
Simon Guest
 
ASP.NET MVC Fundamental
ASP.NET MVC Fundamental
ldcphuc
 
Advanced QUnit - Front-End JavaScript Unit Testing
Advanced QUnit - Front-End JavaScript Unit Testing
Lars Thorup
 
JavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnit
Tasanakorn Phaipool
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
Andy Butland
 
Understanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 
Laws of test automation framework
Laws of test automation framework
vodqancr
 
CQRS на практике. В поиске точки масштабирования и новых метафор
CQRS на практике. В поиске точки масштабирования и новых метафор
Alexander Byndyu
 
Unit and integration Testing
Unit and integration Testing
David Berliner
 
Behavior Driven Development with Cucumber
Behavior Driven Development with Cucumber
Brandon Keepers
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScript
Simon Guest
 

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

Viking academy backbone.js
Viking academy backbone.js
Bert Wijnants
 
Javascript for Wep Apps
Javascript for Wep Apps
Michael Puckett
 
Introduction to Knockoutjs
Introduction to Knockoutjs
jhoguet
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!
Roberto Messora
 
MVC pattern for widgets
MVC pattern for widgets
Behnam Taraghi
 
Give your web apps some backbone
Give your web apps some backbone
RTigger
 
Clean Javascript
Clean Javascript
Ryunosuke SATO
 
Planbox Backbone MVC
Planbox Backbone MVC
Acquisio
 
Backbone.js slides
Backbone.js slides
Ambert Ho
 
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Alex Chaffee
 
Angular js gtg-27feb2013
Angular js gtg-27feb2013
Nitya Narasimhan
 
Rp 6 session 2 naresh bhatia
Rp 6 session 2 naresh bhatia
sapientindia
 
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Fabio Franzini
 
Sugarcoating your frontend one ViewModel at a time
Sugarcoating your frontend one ViewModel at a time
Einar Ingebrigtsen
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
Soós Gábor
 
Architecting non-trivial browser applications (Jazoon 2012)
Architecting non-trivial browser applications (Jazoon 2012)
Marc Bächinger
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
Single Page Applications - Desert Code Camp 2012
Single Page Applications - Desert Code Camp 2012
Adam Mokan
 
Wintellect - Devscovery - Enterprise JavaScript Development 2 of 2
Wintellect - Devscovery - Enterprise JavaScript Development 2 of 2
Jeremy Likness
 
Single Page Application
Single Page Application
Prasad Narasimhan
 
Viking academy backbone.js
Viking academy backbone.js
Bert Wijnants
 
Introduction to Knockoutjs
Introduction to Knockoutjs
jhoguet
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!
Roberto Messora
 
MVC pattern for widgets
MVC pattern for widgets
Behnam Taraghi
 
Give your web apps some backbone
Give your web apps some backbone
RTigger
 
Planbox Backbone MVC
Planbox Backbone MVC
Acquisio
 
Backbone.js slides
Backbone.js slides
Ambert Ho
 
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Alex Chaffee
 
Rp 6 session 2 naresh bhatia
Rp 6 session 2 naresh bhatia
sapientindia
 
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Fabio Franzini
 
Sugarcoating your frontend one ViewModel at a time
Sugarcoating your frontend one ViewModel at a time
Einar Ingebrigtsen
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
Soós Gábor
 
Architecting non-trivial browser applications (Jazoon 2012)
Architecting non-trivial browser applications (Jazoon 2012)
Marc Bächinger
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
Single Page Applications - Desert Code Camp 2012
Single Page Applications - Desert Code Camp 2012
Adam Mokan
 
Wintellect - Devscovery - Enterprise JavaScript Development 2 of 2
Wintellect - Devscovery - Enterprise JavaScript Development 2 of 2
Jeremy Likness
 
Ad

More from Lars Thorup (18)

100 tests per second - 40 releases per week
100 tests per second - 40 releases per week
Lars Thorup
 
SQL or NoSQL - how to choose
SQL or NoSQL - how to choose
Lars Thorup
 
Super fast end-to-end-tests
Super fast end-to-end-tests
Lars Thorup
 
Extreme Programming - to the next-level
Extreme Programming - to the next-level
Lars Thorup
 
Advanced Javascript Unit Testing
Advanced Javascript Unit Testing
Lars Thorup
 
Unit testing legacy code
Unit testing legacy code
Lars Thorup
 
Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"
Lars Thorup
 
Database Schema Evolution
Database Schema Evolution
Lars Thorup
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
Javascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and Sinon
Lars Thorup
 
Continuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScript
Lars Thorup
 
Automated Performance Testing
Automated Performance Testing
Lars Thorup
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
Lars Thorup
 
Agile Contracts
Agile Contracts
Lars Thorup
 
High Performance Software Engineering Teams
High Performance Software Engineering Teams
Lars Thorup
 
Elephant Carpaccio
Elephant Carpaccio
Lars Thorup
 
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 Testing
Lars Thorup
 
100 tests per second - 40 releases per week
100 tests per second - 40 releases per week
Lars Thorup
 
SQL or NoSQL - how to choose
SQL or NoSQL - how to choose
Lars Thorup
 
Super fast end-to-end-tests
Super fast end-to-end-tests
Lars Thorup
 
Extreme Programming - to the next-level
Extreme Programming - to the next-level
Lars Thorup
 
Advanced Javascript Unit Testing
Advanced Javascript Unit Testing
Lars Thorup
 
Unit testing legacy code
Unit testing legacy code
Lars Thorup
 
Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"
Lars Thorup
 
Database Schema Evolution
Database Schema Evolution
Lars Thorup
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
Javascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and Sinon
Lars Thorup
 
Continuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScript
Lars Thorup
 
Automated Performance Testing
Automated Performance Testing
Lars Thorup
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
Lars Thorup
 
High Performance Software Engineering Teams
High Performance Software Engineering Teams
Lars Thorup
 
Elephant Carpaccio
Elephant Carpaccio
Lars Thorup
 
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 Testing
Lars Thorup
 
Ad

Recently uploaded (20)

FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
Powering Multi-Page Web Applications Using Flow Apps and FME Data Streaming
Powering Multi-Page Web Applications Using Flow Apps and FME Data Streaming
Safe Software
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
ICT Frame Magazine Pvt. Ltd.
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Impelsys Inc.
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
Powering Multi-Page Web Applications Using Flow Apps and FME Data Streaming
Powering Multi-Page Web Applications Using Flow Apps and FME Data Streaming
Safe Software
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
ICT Frame Magazine Pvt. Ltd.
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Impelsys Inc.
 

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