Download - Testable, Object-Oriented JavaScript
Testable, Object Oriented
JavaScriptby Jon Kruger
History
The Future
Your typical JavaScript
What is the problem with this?
$("#Name").text("jon");
Widely accepted “best practices”
Object oriented programmingReadable codeSmall classes/filesLoosely coupledUnit testing
F
Ways we can test JavaScript
Cucumber, SpecFlow, Selenium, Watir, etc.
Ways we can test JavaScript
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"); });});
Ways we can test JavaScript
?????????????????
Jasmine
What is a unit test?Tests a small unit of functionalityMust run fastIsolate external dependencies
Problems to solveHow do we deal with the DOMHow do we deal with AJAX callsHow do we run the tests
Basic JavaScript Architecture
DOM
JavaScript
Server
AJAX
Basic JavaScript Architecture
JavaScript
Server
AJAX
DOM
Basic JavaScript Architecture
DOM
JavaScript
Server
AJAX
???????
Basic JavaScript Architecture
DOM
JavaScript
Server
AJAX
???????
Fake DOM
JSView
http://github.com/jonkruger/jsview
Live TDD Action!!!!
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:
getUsernamesetUsernameshowUsernamehideUsernameclickUsernamepressKeyInUsernamekeyDownInUsernameenableUsernamedisableUsername
whenUsernameChangeswhenUsernameClickedwhenUsernameIsClickedwhenUsernameGainsFocuswhenUsernameLosesFocuswhenKeyIsPressedInUsernamewhenKeyDownInUsername
function Client(element, view){ if (view == null) view = new jQueryView("Client", element);
registerObjectProperties(this, view, ['SendButton']); }
The Client class now has the following methods:
showSendButtonhideSendButtonclickSendButtonenableSendButtondisableSendButton
whenSendButtonClickedwhenSendButtonIsClicked
function Client(element, view){ if (view == null) view = new jQueryView("Client", element);
registerList(this, view, ['Tweets']); }
The Client class now has the following methods:
appendToTweetsprependToTweetsgetTweets
<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>
?
Slides, links, code, contact info
Slides: http://jonkruger.com/blogJSView:
http://github.com/jonkruger/jsviewJasmine:
http://pivotal.github.com/jasmine
mail: [email protected]: @JonKruger
Blog: http://jonkruger.com/blog