501 likes | 646 Views
Unit Testing JavaScript. Using Test Driven Development Jon Kruger Email: jon@jonkruger.com Blog: http://jonkruger.com Twitter: JonKruger. Goals of this talk. Explain why you should write unit tests Show you how to write unit tests for JavaScript code
E N D
Unit Testing JavaScript Using Test Driven Development Jon Kruger Email: jon@jonkruger.com Blog: http://jonkruger.com Twitter: JonKruger
Goals of this talk • Explain why you should write unit tests • Show you how to write unit tests for JavaScript code • Show you Test Driven Development in action!
What is a unit test? • Tests a small unit of functionality • Must run fast • Isolate external dependencies using mocks and stubs
What is not a unit test? • Test that runs against external dependencies (e.g. database, UI, file system) • Test that is slow • Web tests, load tests, performance tests
Why write unit tests? • You will write bad code • You (or someone else) will break your code • Someone else will need to understand your code • No compiler for JavaScript • Peace of mind
What's in it for me? • Proof that your code works • Fewer bugs (both now and in the future) • Peace of mind
Why Test Driven Development? • Design • Edge cases • Separation of concerns • Verification • Documentation • Testable code • When you’re “done” your done
The TDD Lifecycle • Get Specs (features or bugs) • Write tests • Watch ‘emfail • Write code • Watch ‘empass • Repeat!
Your new accountability partner http://PairProgrammingBot.com
JavaScript Unit Testing Frameworks JSUnit J3Unit QUnit JSSpec YUI Test Screw-Unit JSNUnit script.aculo.us unit testing TestCase Crosscheck RhinoUnitjqUnit more?
Relevant JavaScript Testing Frameworks QUnit JSSpec YUI Test Screw-Unit
Untestable JavaScript Test won’t run unless it’s run from a page that contains these elements.
Untestable JavaScript Testing this method will pop up an alert box!
Untestable JavaScript Unable to test asynchronous AJAX calls.
Step 8 – Repeat! • Get Specs (features or bugs) • Write tests • Watch ‘emfail • Write code • Watch ‘empass • Repeat!
Hook it up to your .aspx page! • Need to inject UI elements into the tests
What do we have? • I know that my code works • I know what my code is supposed to do - tests are my documentation of my code • I know that my code will continue to work • My classes are well-designed • Tests and good design will mean that it will be easier to make changes to the code • Peace of mind!
Zero Defects • Hold yourself to higher standard • If your code sucks, then stop writing sucky code. • Make quality a priority
Resources • QUnit home page • http://docs.jquery.com/QUnit • Integrating QUnit tests into a continuous integration build • http://tinyurl.com/qunitbuild • MiniSudoku source code • http://jonkruger.com/minisudoku/source.php • My blog • http://jonkruger.com • Send me an email! • jon@jonkruger.com • Twitter • http://twitter.com/jonkruger