More Related Content
Similar to Unit testing js
Similar to Unit testing js (20)
Unit testing js
- 1. © MIRANTIS 20134 PAGE
Making frontend
better:
unit-testing
Aleksandra
Morozova
- 3. © MIRANTIS 2014
Agenda
•Why is unit-testing JS needed?
•Specifics of unit-tests in JS
•Instruments overview
•Best practices and approaches
- 4. Why do we need all these
tests?
© MIRANTIS 2014 PAGE
- 14. © 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
- 15. © MIRANTIS 2014
Basic terms
•Assertion - defining if test is ok or not
expect(26+2).to.equal(28);
- 16. © MIRANTIS 2014
Basic terms
•Fixture - fixed state of software to test,
basis for tests (AJAX)
beforeEach(function() {
loadFixtures(‘dummymarkup.html’);
})
- 17. © MIRANTIS 2014
Basic terms
•method Stub - function with pre-programmed
behaviour
var fn = foo.stub().throws(Error);
expect(fn).to.throw(Error);
- 18. © MIRANTIS 2014
Basic terms
•Spy - function that records arguments,
scope, return value, exception thrown for
all its calls
sinon.spy(cursor, ‘hide’);
- 19. © MIRANTIS 2014
Basic terms
•Mock - fake object with pre-programmed behavior (like
stub) and pre-programmed expectations => stubs+spies
var mock = sinon.mock(“jQuery”);
- 20. © MIRANTIS 2014
Basic Structure
•Setup - beforeEach(), before()
•Prepare data for test
•Call a method
•Check output data
•Tear down - afterEach(), after()
- 21. © MIRANTIS 2014
Setup
before (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’)};)
- 23. © MIRANTIS 2014
Tear down
after(function (done) {
//remove global document object
document = null;
window = null;
done();
})
- 27. © MIRANTIS 2014
Karma
$ npm install karma
Karma with
Require.js
Entire space of
frameworks...
- 31. © MIRANTIS 2014
Best practices
• Fast
• Isolated
• Consistent
• Self-descriptive
• Single responsibility
• No exceptions handling
• Use assertions when needed
- 32. © 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