Post on 29-Jun-2015
description
© MIRANTIS 2013 PAGE © MIRANTIS 2014
Making frontend better:unit-testing
Alexandra Morozova
© MIRANTIS 2014
Preface
© MIRANTIS 2014
Agenda
•Why is unit-testing JS needed?
•Specifics of unit-tests in JS
• Instruments overview
•Best practices and approaches
© MIRANTIS 2014 PAGE
Why do we need all these tests?
© MIRANTIS 2014 PAGE
Big changes done quickly
© MIRANTIS 2014 PAGE
Fuel example
© MIRANTIS 2014 PAGE
Fuel example
© MIRANTIS 2014 PAGE
Step closer to PERFECT CODE
© MIRANTIS 2014 PAGE
Understanding the design
© MIRANTIS 2014 PAGE
Less time for testing
© MIRANTIS 2014 PAGE
Self-documented code
© MIRANTIS 2014 PAGE
Tests allow REFACTORING
© MIRANTIS 2014 PAGE
Testing is FUN!
© MIRANTIS 2014
A few cons
•Slow down the development process
•Share the same blind point with the code
•Do not prove that work one with another
© MIRANTIS 2014
Basic terms
•Assertion - defining if test is ok or not
expect(26+2).to.equal(28);
© MIRANTIS 2014
Basic terms
•Fixture - fixed state of software to test, basis for tests (AJAX)
beforeEach(function() {loadFixtures(‘dummymarkup.html’);
})
© MIRANTIS 2014
Basic terms
•method Stub - function with pre-programmed behaviour
var fn = foo.stub().throws(Error);expect(fn).to.throw(Error);
© MIRANTIS 2014
Basic terms
•Spy - function that records arguments, scope, return value, exception thrown for all its calls
sinon.spy(cursor, ‘hide’);
© MIRANTIS 2014
Basic terms
•Mock - fake object with pre-programmed behavior (like stub) and pre-programmed expectations => stubs+spies
var mock = sinon.mock(“jQuery”);
© MIRANTIS 2014
Basic Structure
•Setup - beforeEach(), before()
•Prepare data for test
•Call a method
•Check output data •Tear down - afterEach(), after()
© MIRANTIS 2014
Setup
© MIRANTIS 2014
Prepare, call & check
© MIRANTIS 2014
Tear down
© MIRANTIS 2014
Instruments
Entire space of frameworks...
© MIRANTIS 2014
Instruments
Entire space of frameworks...
© MIRANTIS 2014
Karma
Entire space of frameworks...
© MIRANTIS 2014
Karma
$ npm install karma
Karma withRequire.js
Entire space of frameworks...
© MIRANTIS 2014
Example: Backbone Model
© MIRANTIS 2014
Example: Backbone Collection
© MIRANTIS 2014
Example: Backbone Collection
© MIRANTIS 2014
Best practices
• Fast• Isolated• Consistent• Self-descriptive• Single responsibility• No exceptions handling• Use assertions when needed
© MIRANTIS 2014
Conclusion
• Each test verifies a small chunk of code
• Unit tests work better in isolation
• Mocks, stubs and spies help us
• Don’t test everything, but write many tests
© MIRANTIS 2013 PAGE
Q&A