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

More Related Content

PDF
DEXCS2022 for preCICE
PPTX
Marine corrosion koushik das
PPTX
A2-5 DMARC レポート送信 milter 紹介と最近の傾向
PDF
Building native mobile apps using web technologies
PDF
Javascript Unit Testting (PHPBenelux 2011-05-04)
PPT
Web App Mvc
PDF
Controller Testing: You're Doing It Wrong
ODP
Focus on the outside, testing in ASP.NET MVC
DEXCS2022 for preCICE
Marine corrosion koushik das
A2-5 DMARC レポート送信 milter 紹介と最近の傾向
Building native mobile apps using web technologies
Javascript Unit Testting (PHPBenelux 2011-05-04)
Web App Mvc
Controller Testing: You're Doing It Wrong
Focus on the outside, testing in ASP.NET MVC

Viewers also liked (15)

PPTX
F# Eye for the C# Guy - DDD North 2013
PPT
JavaScript Unit Testing
PPTX
ASP.NET MVC Fundamental
PDF
Advanced QUnit - Front-End JavaScript Unit Testing
PPTX
Qunit Java script Un
PDF
JavaScript Test-Driven Development (TDD) with QUnit
PPTX
DDD, CQRS and testing with ASP.Net MVC
PDF
Understanding JavaScript Testing
PDF
Laws of test automation framework
PDF
CQRS на практике. В поиске точки масштабирования и новых метафор
PDF
Unit and integration Testing
PDF
Model View Controller (MVC)
PPT
Mvc architecture
PDF
Behavior Driven Development with Cucumber
PDF
Automated Web Testing using JavaScript
F# Eye for the C# Guy - DDD North 2013
JavaScript Unit Testing
ASP.NET MVC Fundamental
Advanced QUnit - Front-End JavaScript Unit Testing
Qunit Java script Un
JavaScript Test-Driven Development (TDD) with QUnit
DDD, CQRS and testing with ASP.Net MVC
Understanding JavaScript Testing
Laws of test automation framework
CQRS на практике. В поиске точки масштабирования и новых метафор
Unit and integration Testing
Model View Controller (MVC)
Mvc architecture
Behavior Driven Development with Cucumber
Automated Web Testing using JavaScript
Ad

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

PDF
Viking academy backbone.js
PPTX
Javascript for Wep Apps
PPTX
Introduction to Knockoutjs
PPTX
MV* presentation frameworks in Javascript: en garde, pret, allez!
PDF
MVC pattern for widgets
PPTX
Give your web apps some backbone
PDF
Clean Javascript
PPTX
Planbox Backbone MVC
PDF
Backbone.js slides
PPT
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
PDF
Angular js gtg-27feb2013
PDF
Rp 6 session 2 naresh bhatia
PPTX
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
KEY
Sugarcoating your frontend one ViewModel at a time
ODP
Javascript frameworks: Backbone.js
PDF
Architecting non-trivial browser applications (Jazoon 2012)
KEY
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
KEY
Single Page Applications - Desert Code Camp 2012
PPTX
Wintellect - Devscovery - Enterprise JavaScript Development 2 of 2
DOCX
Single Page Application
Viking academy backbone.js
Javascript for Wep Apps
Introduction to Knockoutjs
MV* presentation frameworks in Javascript: en garde, pret, allez!
MVC pattern for widgets
Give your web apps some backbone
Clean Javascript
Planbox Backbone MVC
Backbone.js slides
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Angular js gtg-27feb2013
Rp 6 session 2 naresh bhatia
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Sugarcoating your frontend one ViewModel at a time
Javascript frameworks: Backbone.js
Architecting non-trivial browser applications (Jazoon 2012)
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Applications - Desert Code Camp 2012
Wintellect - Devscovery - Enterprise JavaScript Development 2 of 2
Single Page Application
Ad

More from Lars Thorup (18)

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

Recently uploaded (20)

PDF
TicketRoot: Event Tech Solutions Deck 2025
PDF
Slides World Game (s) Great Redesign Eco Economic Epochs.pdf
PDF
FASHION-DRIVEN TEXTILES AS A CRYSTAL OF A NEW STREAM FOR STAKEHOLDER CAPITALI...
PPTX
Blending method and technology for hydrogen.pptx
PPTX
maintenance powerrpoint for adaprive and preventive
PDF
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
PDF
Gestión Unificada de los Riegos Externos
PPTX
Presentation - Principles of Instructional Design.pptx
PDF
State of AI in Business 2025 - MIT NANDA
PPTX
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
PDF
Advancements in abstractive text summarization: a deep learning approach
PDF
ment.tech-How to Develop an AI Agent Healthcare App like Sully AI (1).pdf
PDF
【AI論文解説】高速・高品質な生成を実現するFlow Map Models(Part 1~3)
PDF
The Digital Engine Room: Unlocking APAC’s Economic and Digital Potential thro...
PDF
Examining Bias in AI Generated News Content.pdf
PDF
Applying Agentic AI in Enterprise Automation
PDF
Peak of Data & AI Encore: Scalable Design & Infrastructure
PDF
Human Computer Interaction Miterm Lesson
PDF
Decision Optimization - From Theory to Practice
PDF
Altius execution marketplace concept.pdf
TicketRoot: Event Tech Solutions Deck 2025
Slides World Game (s) Great Redesign Eco Economic Epochs.pdf
FASHION-DRIVEN TEXTILES AS A CRYSTAL OF A NEW STREAM FOR STAKEHOLDER CAPITALI...
Blending method and technology for hydrogen.pptx
maintenance powerrpoint for adaprive and preventive
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
Gestión Unificada de los Riegos Externos
Presentation - Principles of Instructional Design.pptx
State of AI in Business 2025 - MIT NANDA
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
Advancements in abstractive text summarization: a deep learning approach
ment.tech-How to Develop an AI Agent Healthcare App like Sully AI (1).pdf
【AI論文解説】高速・高品質な生成を実現するFlow Map Models(Part 1~3)
The Digital Engine Room: Unlocking APAC’s Economic and Digital Potential thro...
Examining Bias in AI Generated News Content.pdf
Applying Agentic AI in Enterprise Automation
Peak of Data & AI Encore: Scalable Design & Infrastructure
Human Computer Interaction Miterm Lesson
Decision Optimization - From Theory to Practice
Altius execution marketplace concept.pdf

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