Showing posts with label karma. Show all posts
Showing posts with label karma. Show all posts

Thursday, February 6, 2014

AngularJS Testing: Consolidating Injections

ASSUMPTION: You are familiar with the following frameworks

Angularjs
Jasmine
Nodejs
Karma
Grunt

With AngularJS, you get Dependency Injection - duh, great post so far…

You love DI so you start cranking out tests injecting and mocking everything under the sun.  You wake up 3 months later and you have a nasty code smell: Copy Paste Monsters are everywhere

Solution: Try your best not to be so damn lazy…I fight it every 2 seconds…

Not Ideal


  • you can see this spec really contains 2 simple tests, each injecting dependencies into the test ($rootScope, $controller, clientOrderModel)
  • the controller probably displays contact information and validation is needed for the contact email (we’re just checking if it’s present, not real email validation: have a heart)
  • you created the first test and went through your normal: red -> green -> refactor…you refactored the controller/service/thingy but forgot to refactor the test…who cares, it’s green - move on already…then time for test two - reach for your friend the copy paste monster and you’re flying high
  • at first glance this might not seem like a big deal but over the span of 3 months, each couple of sprints adding new developers who themselves want to copy/paste from the previous guy because their too afraid to mess something up…and BAM: you have way too much code everywhere and you forgot to stay DRY
  • tests are harder to maintain, read, etc. - same old story presented a million times by testing authors over the last 15 years
Better


  • you can see we’ve moved each of the inject statements into 1 beforeEach, we’re also able to do this because each test requires the same dependencies
  • you can also see each of the tests is much easier to read, really only a couple of lines
  • a nice caveat to this approach: folks coming in after you will be more willing to write tests too, especially if they’re less complex, easier to write & understand, blah…
Special Note

No, you haven’t won anything for actually reading this BUT pay close attention to the customerOrder object being used in each of the tests. Please remember to always reset your mocked objects in a beforeEach clause.

Why?

Because objects are reference types, each change you make to the object will affect other tests - assuming you are referencing the same object in multiple tests: BAD.  Using the beforeEach clause will ensure each test starts out pristine.