This document discusses JavaScript unit testing with QUnit and Sinon. It introduces Lars Thorup and his background in software development, testing, and coaching. It then provides an overview of unit testing, explaining why it is beneficial and how to implement it. Finally, it demonstrates various QUnit and Sinon techniques for writing tests, including assertions, spies, stubs, mocks, asynchronous code, the DOM, and advanced mocking.
2. Who is Lars Thorup?
● Software developer/architect
● JavaScript, C# and C++
● Test Driven Development
● Coaching teams in agile
engineering practices
● Assessing software projects
and companies
● Founder and CEO of
BestBrains and ZeaLake
4. ● What is unit testing about?
● Express expected behaviour of the code we write
● Why is unit testing a good thing?
● Faster development
● Find and fix bugs faster
● Prevent bugs from reappearing
● Improve the design of our software
● Reliable documentation
● How do we do unit testing?
● Write test code
● Run the tests automatically
Why are we here today?
5. QUnit - tests and fixtures
module('module name', {
setup: function () {
this.account = new Account(4711);
}
});
test('test name, function () {
equal(this.account.id, 4711);
});
test('...', function () {
...
});
7. Sinon - spies, stubs and mocks
Math.randomBelow = function (n) {
return Math.floor(Math.random() * n);
};
module('util.random', {
setup: function () {
sinon.stub(Math, 'random').returns(0.85);
},
teardown: function () {
Math.random.restore();
}
});
test('randomBelow', function () {
equal(Math.randomBelow(6), 5, '6');
});
8. DOM
module('Control.Button', {
setup: function () {
$('<button id="next"></button>')
.appendTo('#qunit-fixture');
this.button = new Control.Button('#next', {
text: 'Next'
});
}
});
test('constructor', function () {
equal($('#next').attr('text'), 'Next', '.text');
});
● #qunit-fixture is emptied before each test
12. Unit testing philosophy
● Behaviour first
● makes more sense than "Test first"
● Structure of test programs
● Given <precondition>
● When <invocation>
● Then <expectation>
● High level as well as low level
● Test user stories and requirements
● Test class design and algorithms
● Communicate intent
● Fast feedback