javascript testing: tools of the trade
TRANSCRIPT
The suite
(function (rps) {
‘use strict’;
describe(‘when playing rock-paper-scissors’, function() {
});
}(RockPaperScissors)); // the module under test
Setup and tear downdescribe(‘when playing rock-paper-scissors’, function() {
var foo = ‘’;
beforeEach(function() {
foo = ‘bar’;
});
afterEach(function() {
foo = ‘’;
});
});
The specification (spec)
describe(‘when playing rock-paper-scissors’, function() {
it(‘will show that rock wins scissors’, function() {
var result = rps.whoWins(‘rock’, ‘scissors’);
expect(result).toEqual(1);
})
});
Mocking dependencies
it(‘will show that rock wins scissors’, function() {
var choice = ‘rock’;
spyOn(rps, ‘validate’).and.callFake(function() { // Jasmine 2.0 syntax
return choice;
});
spyOn(rps, ‘whoWins’).andCallFake(function() { // Jasmine 1.x syntax
$(document).trigger(‘score:user1’);
});
Matchers
Common matchers
expect(true).toBe(true);
expect(true).not.toBe(fase);
.toEqual
...
jQuery matchers
Using jasmine-jquery module
expect($(‘#info’)).toBeVisible();
expect($(‘#info’)).toHaveClass();
expect($(‘#myField’)).toHaveValue(‘123’);
Custom Matchers
var customMatchers = {
toBeActive: function() {
return {
compare: function(item) {
...
}
}
}
};
beforeEach(function() {
jasmine.addMatchers(customMatchers);
});
expect($(‘#element’)).toBeActive();
expect($(‘#element’)).not.toBeActive();
Enter the Karma
“Karma is essentially a tool which spawns a web server that executes source code against test code for each of the
browsers connected. The results for each test against each browser are examined and displayed via the command line to
the developer such that they can see which browsers and tests passed or failed.”
$ karma start
The browsers
● Google Chrome
● Mozilla Firefox
● Safari (only on OS X)
● Internet Explorer (yes, IE too, but only on Win machines)
and
● Phantom JS -> the headless one
Protractor: End to end testing (e2e)
Designed basically for AngularJS e2e testing,
runs tests in a real browser.
Simulates user interactions
Can use any test framework,
but works smoothly with Jasmine
It can also be used to test
non-angularjs applications
Example protractor test
beforeEach(function () {
browser.ignoreSynchronization = true;
browser.get(‘http://localhost:9000’);
});
it(‘should show …’, function() {
element(by.id(‘myChoice’))
.sendKeys(‘stone’);
element(by.css(‘.btn’)).click();
alert = element.all(by.css(‘.alert’))
expect(alert.count()).toBe(1);
});
Resources
The repo of this tests and exercises:
https://github.com/juanmaorta/rockpaperscissors.git
Jasmine: http://jasmine.github.io/
Karma: http://karma-runner.github.io/0.13/index.html
Protractor: https://angular.github.io/protractor/#/