SlideShare a Scribd company logo
by Jon Kruger
Testable, Object-Oriented JavaScript
Testable, Object-Oriented JavaScript
Testable, Object-Oriented JavaScript
$("#Name").text("jon");
   Object oriented programming
   Readable code
   Small classes/files
   Loosely coupled
   Unit testing




                       F
   Cucumber, SpecFlow, Selenium, Watir, etc.
   Inject HTML in our tests

describe("Testing by injecting HTML into jQuery", function()
{
  it("should work, but it's kind of a pain", function()
  {
    element = $('<div>text</div>');
    element.text("some more text");
    expect(element.text()).toEqual("some more text");
  });
});
   ?????????????????
Testable, Object-Oriented JavaScript
   Tests a small unit of functionality
   Must run fast
   Isolate external dependencies
   How do we deal with the DOM
   How do we deal with AJAX calls
   How do we run the tests
DOM
JavaScript
      AJAX

 Server
DOM
JavaScript
      AJAX

 Server
DOM
      ???????

JavaScript
      AJAX

 Server
DOM        Fake DOM
       ???????

  JavaScript
            AJAX

      Server
http://github.com/jonkruger/jsview
FTW!!!!
function Client(element, view)
{
  if (view == null)
    view = new jQueryView("Client", element);

    registerObjectProperties(this, view, ['Username']);
}

The Client class now has the following methods:
getUsername                          whenUsernameChanges
setUsername                          whenUsernameClicked
showUsername                         whenUsernameIsClicked
hideUsername                         whenUsernameGainsFocus
clickUsername                        whenUsernameLosesFocus
pressKeyInUsername                   whenKeyIsPressedInUsername
keyDownInUsername                    whenKeyDownInUsername
enableUsername
disableUsername
function Client(element, view)
{
  if (view == null)
    view = new jQueryView("Client", element);

    registerObjectProperties(this, view, ['SendButton']);
}

The Client class now has the following methods:
showSendButton                       whenSendButtonClicked
hideSendButton                       whenSendButtonIsClicked
clickSendButton
enableSendButton
disableSendButton
function Client(element, view)
{
  if (view == null)
    view = new jQueryView("Client", element);

    registerList(this, view, ['Tweets']);
}

The Client class now has the following methods:
appendToTweets
prependToTweets
getTweets
<html>
<head>
  <script language="javascript">
    $(document).ready(function()
    {
      entryForm = new EntryForm($("#EntryForm"));
    });
  </script>
</head>
<body>
  <div id="EntryForm">
    First Name:<br/>
    <input type="text" class="EntryForm-FirstName" /><br/>
    <br/>
    Last Name:<br/>
    <input type="text" class="EntryForm-LastName" />
  </div>
</body>
</html>
Testable, Object-Oriented JavaScript
Slides: http://jonkruger.com/blog
JSView: http://github.com/jonkruger/jsview
Jasmine: http://pivotal.github.com/jasmine

        mail: jon@jonkruger.com
          Twitter: @JonKruger
     Blog: http://jonkruger.com/blog

More Related Content

What's hot (20)

KEY
Why ruby
rstankov
 
PDF
Web Crawling with NodeJS
Sylvain Zimmer
 
KEY
Ruby/Rails
rstankov
 
PDF
05 JavaScript #burningkeyboards
Denis Ristic
 
PPTX
jQuery
Dileep Mishra
 
KEY
Week 4 - jQuery + Ajax
baygross
 
PDF
jQuery in 15 minutes
Simon Willison
 
PDF
06 jQuery #burningkeyboards
Denis Ristic
 
PPT
jQuery
Mohammed Arif
 
PDF
Javascript Frameworks for Joomla
Luke Summerfield
 
PPTX
JavaScript Promises
L&T Technology Services Limited
 
PDF
Joe Walker Interactivewebsites Cometand Dwr
deimos
 
PPTX
jQuery Best Practice
chandrashekher786
 
PDF
Remy Sharp The DOM scripting toolkit jQuery
deimos
 
PDF
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Thomas Fuchs
 
PDF
JavaScript Promise
Joseph Chiang
 
PPTX
jQuery
Jay Poojara
 
PDF
Basic Tutorial of React for Programmers
David Rodenas
 
Why ruby
rstankov
 
Web Crawling with NodeJS
Sylvain Zimmer
 
Ruby/Rails
rstankov
 
05 JavaScript #burningkeyboards
Denis Ristic
 
Week 4 - jQuery + Ajax
baygross
 
jQuery in 15 minutes
Simon Willison
 
06 jQuery #burningkeyboards
Denis Ristic
 
Javascript Frameworks for Joomla
Luke Summerfield
 
JavaScript Promises
L&T Technology Services Limited
 
Joe Walker Interactivewebsites Cometand Dwr
deimos
 
jQuery Best Practice
chandrashekher786
 
Remy Sharp The DOM scripting toolkit jQuery
deimos
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Thomas Fuchs
 
JavaScript Promise
Joseph Chiang
 
jQuery
Jay Poojara
 
Basic Tutorial of React for Programmers
David Rodenas
 

Similar to Testable, Object-Oriented JavaScript (20)

PDF
jQuery secrets
Bastian Feder
 
PDF
Introducing jQuery
Wildan Maulana
 
PDF
Automated testing for client-side - Adam Klein, 500 Tech
Codemotion Tel Aviv
 
PDF
Client side unit tests - using jasmine & karma
Adam Klein
 
ODP
Jquery- One slide completing all JQuery
Knoldus Inc.
 
PDF
international PHP2011_Bastian Feder_jQuery's Secrets
smueller_sandsmedia
 
PDF
jQuery secrets
Bastian Feder
 
PDF
Introduction to jQuery
Nagaraju Sangam
 
KEY
amsterdamjs - jQuery 1.5
mennovanslooten
 
PPTX
Jquery Complete Presentation along with Javascript Basics
EPAM Systems
 
PDF
jQuery and Rails, Sitting in a Tree
adamlogic
 
PDF
jQuery
Ivano Malavolta
 
PDF
Kakunin E2E framework showcase
The Software House
 
PDF
Magento2&amp;java script (2)
EvgeniyKapelko1
 
PDF
Web Components Everywhere
Ilia Idakiev
 
PPTX
Jquery plugin development
Faruk Hossen
 
PPTX
J Query The Write Less Do More Javascript Library
rsnarayanan
 
PDF
Clean Javascript
Ryunosuke SATO
 
PPTX
Unit3.pptx
AnamikaRai59
 
jQuery secrets
Bastian Feder
 
Introducing jQuery
Wildan Maulana
 
Automated testing for client-side - Adam Klein, 500 Tech
Codemotion Tel Aviv
 
Client side unit tests - using jasmine & karma
Adam Klein
 
Jquery- One slide completing all JQuery
Knoldus Inc.
 
international PHP2011_Bastian Feder_jQuery's Secrets
smueller_sandsmedia
 
jQuery secrets
Bastian Feder
 
Introduction to jQuery
Nagaraju Sangam
 
amsterdamjs - jQuery 1.5
mennovanslooten
 
Jquery Complete Presentation along with Javascript Basics
EPAM Systems
 
jQuery and Rails, Sitting in a Tree
adamlogic
 
Kakunin E2E framework showcase
The Software House
 
Magento2&amp;java script (2)
EvgeniyKapelko1
 
Web Components Everywhere
Ilia Idakiev
 
Jquery plugin development
Faruk Hossen
 
J Query The Write Less Do More Javascript Library
rsnarayanan
 
Clean Javascript
Ryunosuke SATO
 
Unit3.pptx
AnamikaRai59
 
Ad

More from Jon Kruger (7)

PPTX
The Business of You: 10 Steps To Run Your Career Like a Business
Jon Kruger
 
PPTX
Developing an Automated Testing Strategy
Jon Kruger
 
PPTX
A Whole Team Approach To Testing
Jon Kruger
 
PPTX
An ATDD Case Study
Jon Kruger
 
PPTX
Productivity Boosters for .NET Developers
Jon Kruger
 
PPTX
Test-Driven Development In Action
Jon Kruger
 
PPTX
Advanced Object-Oriented/SOLID Principles
Jon Kruger
 
The Business of You: 10 Steps To Run Your Career Like a Business
Jon Kruger
 
Developing an Automated Testing Strategy
Jon Kruger
 
A Whole Team Approach To Testing
Jon Kruger
 
An ATDD Case Study
Jon Kruger
 
Productivity Boosters for .NET Developers
Jon Kruger
 
Test-Driven Development In Action
Jon Kruger
 
Advanced Object-Oriented/SOLID Principles
Jon Kruger
 
Ad

Recently uploaded (20)

PDF
Shuen Mei Parth Sharma Boost Productivity, Innovation and Efficiency wit...
AWS Chicago
 
PPTX
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
PDF
How a Code Plagiarism Checker Protects Originality in Programming
Code Quiry
 
PDF
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
DOCX
TLE9 COOKERY DLL WEEK3 technology and li
jamierha cabaero
 
PPTX
Lecture 5 - Agentic AI and model context protocol.pptx
Dr. LAM Yat-fai (林日辉)
 
PPTX
Machine Learning Benefits Across Industries
SynapseIndia
 
PPTX
Extensions Framework (XaaS) - Enabling Orchestrate Anything
ShapeBlue
 
PPTX
UI5Con 2025 - Beyond UI5 Controls with the Rise of Web Components
Wouter Lemaire
 
PDF
CIFDAQ'S Token Spotlight for 16th July 2025 - ALGORAND
CIFDAQ
 
PDF
OpenInfra ID 2025 - Are Containers Dying? Rethinking Isolation with MicroVMs.pdf
Muhammad Yuga Nugraha
 
PDF
2025-07-15 EMEA Volledig Inzicht Dutch Webinar
ThousandEyes
 
PPTX
Simplifying End-to-End Apache CloudStack Deployment with a Web-Based Automati...
ShapeBlue
 
PDF
HR agent at Mediq: Lessons learned on Agent Builder & Maestro by Tacstone Tec...
UiPathCommunity
 
PDF
GITLAB-CICD_For_Professionals_KodeKloud.pdf
deepaktyagi0048
 
PDF
Meetup Kickoff & Welcome - Rohit Yadav, CSIUG Chairman
ShapeBlue
 
PDF
Novus-Safe Pro: Brochure-What is Novus Safe Pro?.pdf
Novus Hi-Tech
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
PDF
How Current Advanced Cyber Threats Transform Business Operation
Eryk Budi Pratama
 
Shuen Mei Parth Sharma Boost Productivity, Innovation and Efficiency wit...
AWS Chicago
 
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
How a Code Plagiarism Checker Protects Originality in Programming
Code Quiry
 
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
TLE9 COOKERY DLL WEEK3 technology and li
jamierha cabaero
 
Lecture 5 - Agentic AI and model context protocol.pptx
Dr. LAM Yat-fai (林日辉)
 
Machine Learning Benefits Across Industries
SynapseIndia
 
Extensions Framework (XaaS) - Enabling Orchestrate Anything
ShapeBlue
 
UI5Con 2025 - Beyond UI5 Controls with the Rise of Web Components
Wouter Lemaire
 
CIFDAQ'S Token Spotlight for 16th July 2025 - ALGORAND
CIFDAQ
 
OpenInfra ID 2025 - Are Containers Dying? Rethinking Isolation with MicroVMs.pdf
Muhammad Yuga Nugraha
 
2025-07-15 EMEA Volledig Inzicht Dutch Webinar
ThousandEyes
 
Simplifying End-to-End Apache CloudStack Deployment with a Web-Based Automati...
ShapeBlue
 
HR agent at Mediq: Lessons learned on Agent Builder & Maestro by Tacstone Tec...
UiPathCommunity
 
GITLAB-CICD_For_Professionals_KodeKloud.pdf
deepaktyagi0048
 
Meetup Kickoff & Welcome - Rohit Yadav, CSIUG Chairman
ShapeBlue
 
Novus-Safe Pro: Brochure-What is Novus Safe Pro?.pdf
Novus Hi-Tech
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
How Current Advanced Cyber Threats Transform Business Operation
Eryk Budi Pratama
 

Testable, Object-Oriented JavaScript

  • 6. Object oriented programming  Readable code  Small classes/files  Loosely coupled  Unit testing F
  • 7. Cucumber, SpecFlow, Selenium, Watir, etc.
  • 8. Inject HTML in our tests describe("Testing by injecting HTML into jQuery", function() { it("should work, but it's kind of a pain", function() { element = $('<div>text</div>'); element.text("some more text"); expect(element.text()).toEqual("some more text"); }); });
  • 9. ?????????????????
  • 11. Tests a small unit of functionality  Must run fast  Isolate external dependencies
  • 12. How do we deal with the DOM  How do we deal with AJAX calls  How do we run the tests
  • 13. DOM JavaScript AJAX Server
  • 14. DOM JavaScript AJAX Server
  • 15. DOM ??????? JavaScript AJAX Server
  • 16. DOM Fake DOM ??????? JavaScript AJAX Server
  • 19. function Client(element, view) { if (view == null) view = new jQueryView("Client", element); registerObjectProperties(this, view, ['Username']); } The Client class now has the following methods: getUsername whenUsernameChanges setUsername whenUsernameClicked showUsername whenUsernameIsClicked hideUsername whenUsernameGainsFocus clickUsername whenUsernameLosesFocus pressKeyInUsername whenKeyIsPressedInUsername keyDownInUsername whenKeyDownInUsername enableUsername disableUsername
  • 20. function Client(element, view) { if (view == null) view = new jQueryView("Client", element); registerObjectProperties(this, view, ['SendButton']); } The Client class now has the following methods: showSendButton whenSendButtonClicked hideSendButton whenSendButtonIsClicked clickSendButton enableSendButton disableSendButton
  • 21. function Client(element, view) { if (view == null) view = new jQueryView("Client", element); registerList(this, view, ['Tweets']); } The Client class now has the following methods: appendToTweets prependToTweets getTweets
  • 22. <html> <head> <script language="javascript"> $(document).ready(function() { entryForm = new EntryForm($("#EntryForm")); }); </script> </head> <body> <div id="EntryForm"> First Name:<br/> <input type="text" class="EntryForm-FirstName" /><br/> <br/> Last Name:<br/> <input type="text" class="EntryForm-LastName" /> </div> </body> </html>
  • 24. Slides: http://jonkruger.com/blog JSView: http://github.com/jonkruger/jsview Jasmine: http://pivotal.github.com/jasmine mail: jon@jonkruger.com Twitter: @JonKruger Blog: http://jonkruger.com/blog

Editor's Notes

  • #2: How many of you like writing JavaScript as much as you do your primary language?Why don’t you like it as much?How many of you write tests for your JavaScript? - What kinds of things are you testing? (logic code, injecting HTML, DOM interactions, ajax, etc.)How many of you have written JavaScript with OO objects?-Why/why not?
  • #3: - Browser inconsistencies (e.g. document.getElementById(), document.all)- We used to not have jQuery
  • #4: Many more single-page client-side rich applications written in JavaScriptYou use these and think they are awesome (Gmail, Google Maps, Outlook Web Access newer versions)HTML5 will allow you to do things that you couldn’t do before in the browser (store data locally, richer graphics, etc.)Mobile websites – you don’t need to build apps for 4 mobile platformsIf you had to do one of these, how would you do it?
  • #5: -What problems do we have when we write JavaScript like this?-Hard to read-Breaks when you change DOM attributes (id, class, etc.)Maybe you move the mess into a separate file, in which case it’s still a mess (you just don’t have to look at it as much)You can do this for simple JavaScript and get away with it, of course (as long as you don’t want to test it with a JavaScript test)
  • #6: What problems would you have if you wanted to write tests for this code?-You would have to have the DOM for the selector to work!-You have to know specifics about what your DOM is going to look like (to some extent)-We might not be able to use an ID selector because we might need to have something else use the id property (e.g. 3rd party controls, old WebForms)
  • #7: We need to do something about this:
  • #8: -These tools are good for end-to-end testing-They won’t help you design your JavaScript-Sometimes it’s easier to test scenarios by testing JavaScript (same reason you write unit tests in server-side code vs. using the browser tools)
  • #10: We need a better way. I want to be able to write my tests first, before I even know what my HTML page looks like.
  • #11: -Reads like RSpec-Ruby gem-Community involvement
  • #14: We have an interface between JavaScript and the server (AJAX), but what is the interface between the JavaScript and the DOM?
  • #15: Typical JavaScript tends to have the JavaScript very tightly coupled to the DOM.
  • #16: How do we separate JavaScript and the DOM?
  • #17: How can we write JavaScript code that will run against the real DOM in production and against a fake DOM in our tests?What things do we typically do with the DOM in JavaScript?Find elementsGet/set textEnable/disable elementsShow/hide elementsEtc.
  • #18: The abstraction layer between your JavaScript and jQuery/the DOMConvention over configurationMakes testing first easier
  • #23: Link DOM elements to the registered properties