unit testing js

Download Unit testing js

Post on 29-Jun-2015




0 download

Embed Size (px)


  • 1. MIRANTIS 20134 PAGEMaking frontendbetter:unit-testingAleksandraMorozova

2. MIRANTIS 2014Preface 3. MIRANTIS 2014AgendaWhy is unit-testing JS needed?Specifics of unit-tests in JSInstruments overviewBest practices and approaches 4. Why do we need all thesetests? MIRANTIS 2014 PAGE 5. Big changes done quickly MIRANTIS 2014 PAGE 6. Fuel example MIRANTIS 2014 PAGE 7. Fuel example MIRANTIS 2014 PAGE 8. Step closer to PERFECTCODE MIRANTIS 2014 PAGE 9. Understanding the design MIRANTIS 2014 PAGE 10. MIRANTIS 2014 PAGELess timefor testing 11. Self-documented code MIRANTIS 2014 PAGE 12. Tests allowREFACTORING MIRANTIS 2014 PAGE 13. Testing is FUN! MIRANTIS 2014 PAGE 14. MIRANTIS 2014A few consSlow down the development processShare the same blind point with the codeDo not prove that work one with another 15. MIRANTIS 2014Basic termsAssertion - defining if test is ok or notexpect(26+2).to.equal(28); 16. MIRANTIS 2014Basic termsFixture - fixed state of software to test,basis for tests (AJAX)beforeEach(function() {loadFixtures(dummymarkup.html);}) 17. MIRANTIS 2014Basic termsmethod Stub - function with pre-programmedbehaviourvar fn = foo.stub().throws(Error);expect(fn).to.throw(Error); 18. MIRANTIS 2014Basic termsSpy - function that records arguments,scope, return value, exception thrown forall its callssinon.spy(cursor, hide); 19. MIRANTIS 2014Basic termsMock - fake object with pre-programmed behavior (likestub) and pre-programmed expectations => stubs+spiesvar mock = sinon.mock(jQuery); 20. MIRANTIS 2014Basic StructureSetup - beforeEach(), before()Prepare data for testCall a methodCheck output dataTear down - afterEach(), after() 21. MIRANTIS 2014Setupbefore (function() {console.log(before test)};)test(first test,function() {console.log(first test);});test(second test,function() {console.log(second test);});afterEach(function() {console.log(after each)};) 22. Prepare, call & check MIRANTIS 2014 23. MIRANTIS 2014Tear downafter(function (done) {//remove global document objectdocument = null;window = null;done();}) 24. MIRANTIS 2014InstrumentsEntire space offrameworks... 25. MIRANTIS 2014InstrumentsEntire space offrameworks... 26. MIRANTIS 2014KarmaEntire space offrameworks... 27. MIRANTIS 2014Karma$ npm install karmaKarma withRequire.jsEntire space offrameworks... 28. Example: Backbone Model MIRANTIS 2014 29. Example: Backbone Collection MIRANTIS 2014 30. Example: Backbone Collection MIRANTIS 2014 31. MIRANTIS 2014Best practices Fast Isolated Consistent Self-descriptive Single responsibility No exceptions handling Use assertions when needed 32. MIRANTIS 2014Conclusion Each test verifies a small chunk of code Unit tests work better in isolation Mocks, stubs and spies help us Dont test everything, but write many tests 33. Q&A MIRANTIS 2013 PAGE