Date post: | 13-Jul-2015 |
Category: |
Technology |
Upload: | thomas-junghans |
View: | 370 times |
Download: | 2 times |
Frontend. JavaScript. Unit. Testing. Namics.
Thomas Junghans. Senior Frontend Engineer. 3. September 2013
Why test? More confidence in code Tests are a kind of documentation Tests help find bugs Refactor without worrying
No time to test Don’t aim to test everything We always have time to…
…test a little. …test as much as possible.
Few tests are better then no tests
Writing tests is easy, right?! Right! Tests must be easy to write Tests must be easy to understand Writing tests needs a little practice Writing tests should become natural
Keep it simple stupid (KISS)
If testing is a pain you, are doing it wrong! If testing is too complicated, you are doing it wrong! It has to be easy, otherwise you are doing it wrong J
Reduce dependencies
Keep JS-dependencies to a minimum
Does your code really depend on jQuery or similar?
The "lighter" the tests, the better and quicker
Avoid fixtures DOM access is expensive Fixtures need maintenance Keep fixtures as small as possible The fixture is not the test subject
Only test code you wrote Everyone should test their own code Don’t test code you didn’t write Don’t test code that has already been tested
Quote
“When externalizing business-to-UI logic into separate classes, it’s also much easier to test.” -‐ Stephan Schmidt, 27.11.2007, h#p://codemonkeyism.com/people-‐dont-‐get-‐the-‐difference-‐between-‐business-‐and-‐ui-‐logic/
Separation of Concerns http://en.wikipedia.org/wiki/Separation_of_concerns Split UI and Business Logic to allow for unit testing Testing Business Logic is easy Testing UI is not (so easy)
Bad example
Tight coupling between UI and logic The values of .augend and .addend cannot be tested The sum cannot be tested The logic of adding to values together cannot be reused else where
$('button.calc').on('click', function (e) {! var sum = $('input.augend').val() + ! $('input.addend').val();!! $('input.sum').val(sum);!});!
Good Better example
• The logic has been moved to the function add • The function add can now easily be tested • The function add can be reused • (There's still more decoupling to do, but we'll leave that for now)
function add(a, b) {! return a + b;!}!!$('button.calc').on('click', function (e) {! var augend = $('input.augend').val(),! addend = $('input.addend').val(),!
! ! sum = add(augend, addend);!! $('input.sum').val(sum);!});!
Advantages of QUnit Small footprint (1 x JS, 1 x CSS) Easy to use – ok(expression, ‘comment’); – strictEqual(iReturnTrue(), true, 'Should be true');
Viewable in browser Automation possible using GruntJS