SlideShare una empresa de Scribd logo
1 de 45
Jasmine
Qué es?
Qué es?
"behavior-driven development framework for
testing JavaScript code"
Qué es?
"behavior-driven development framework for
testing JavaScript code"
http://github.com/pivotal/jasmine
Qué es?
"behavior-driven development framework for
testing JavaScript code"
http://github.com/pivotal/jasmine
● sintaxis simple
● no depende de otros frameworks js ni de existencia de DOM
Ejemplo
function helloWorld(){
return 'Hello World!'
}
describe('HelloWorld', function(){
it('returns hello world message', function(){
expect(helloWorld()).toEqual('Hello World!')
});
});
Ejemplo - Passing
Ejemplo
function helloWorld(){
return 'Bye Bye World!'
}
describe('HelloWorld', function(){
it('returns hello world message', function(){
expect(helloWorld()).toEqual('Hello World!')
});
});
Ejemplo - Failing
Suite - Spec - Expectation
Una suite está compuesta por:
● al menos un bloque describe
● que contiene bloques it (specs)
● que contienen expectations
describe('HelloWorld', function(){
it('returns hello world message', function(){
expect(helloWorld()).toEqual('Hello World!')
});
});
Setup and Teardown
describe('MyObject', function() {
var obj = new MyObject();
beforeEach(function() {
obj.setState('fixed');
});
it('changes state', function() {
obj.setState('broken');
expect(obj.getState()).toEqual('broken');
})
it("adds states", function() {
obj.addState('packaged');
expect(obj.getState()).toEqual(['fixed', 'packaged']);
})
});
Matchers
expects(x).toEqual(y)
expects(x).toBe(y)
expect(x).toContain(y)
expect(x).toBeTruthy()
expect(x).toBeFalsy(
expect(x).toBeDefined()
expect(x).toBeUndefined()
expect(x).toBeNull()
Matchers
expects(x).toEqual(y)
expects(x).toBe(y)
expect(x).toBeTruthy()
expect(x).toBeFalsy()
expect(x).toBeDefined()
expect(x).toBeUndefined()
expect(x).toBeNull()
expect(x).toContain(y)
Matchers
expects(x).toEqual(y)
expects(x).toBe(y)
expect(x).toBeTruthy()
expect(x).toBeFalsy()
expect(x).toBeDefined()
expect(x).toBeUndefined()
expect(x).toBeNull()
expect(x).toContain(y)
Matchers
expects(x).toEqual(y)
expects(x).toBe(y)
expect(x).toBeTruthy()
expect(x).toBeFalsy()
expect(x).toBeDefined()
expect(x).toBeUndefined()
expect(x).toBeNull()
expect(x).toContain(y)
Matchers
expect(x).toBeLessThan(y)
expect(x).toBeGreaterThan(y)
expect(x).toMatch(pattern);
expect(function(){fn();}).toThrow(e);
// todos los matchers se pueden invertir
expect(x).not.toEqual(y)
expect(x).not.toMatch(pattern)
Matchers
expect(x).toBeLessThan(y)
expect(x).toBeGreaterThan(y)
expect(x).toMatch(pattern);
expect(function(){fn();}).toThrow(e);
// todos los matchers se pueden invertir
expect(x).not.toEqual(y)
expect(x).not.toMatch(pattern)
Matchers
expect(x).toBeLessThan(y)
expect(x).toBeGreaterThan(y)
expect(x).toMatch(pattern);
expect(function(){fn();}).toThrow(e);
// todos los matchers se pueden invertir
expect(x).not.toEqual(y)
expect(x).not.toMatch(pattern)
Matchers
expect(x).toBeLessThan(y)
expect(x).toBeGreaterThan(y)
expect(x).toMatch(pattern);
expect(function(){fn();}).toThrow(e);
// todos los matchers se pueden invertir
expect(x).not.toEqual(y)
expect(x).not.toMatch(pattern)
Custom matchers
describe('Numbers Module', function() {
beforeEach(function() {
this.addMatchers({
toBeDivisibleByTwo: function() {
return (this.actual % 2) === 0;
}
});
});
it('is divisible by 2', function() {
expect(gimmeANumber()).toBeDivisibleByTwo();
});
});
Spies
● test doubles
Spies
● test doubles
● reportar que fueron invocados
Spies
● test doubles
● reportar que fueron invocados
● reportar cuantas veces fueron invocados
Spies
● test doubles
● reportar que fueron invocados
● reportar cuantas veces fueron invocados
● reportar con qué parámetros fueron invocados
Spies
● test doubles
● reportar que fueron invocados
● reportar cuantas veces fueron invocados
● reportar con qué parámetros fueron invocados
● si se quiere, invocar al método que están reemplazando
Spies - Ejemplo
function Player() {
this.isPlaying = false;
}
Player.prototype.play = function(song) {
this.currentlyPlayingSong = song;
this.isPlaying = true;
};
Player.prototype.pause = function() {
this.isPlaying = false;
};
Spies - Ejemplo
Player.prototype.togglePlay = function(song) {
if (this.isPlaying) {
this.pause();
}
else {
this.play(song);
}
}
Spies - Ejemplo
describe('tooglePlay', function() {
beforeEach(function() {
player.play(song);
});
it('should pause if it's playing', function() {
spyOn(player, 'pause'); // define the spy
player.togglePlay(song);
expect(player.pause).toHaveBeenCalled();
});
});
Spies - Comportamiento
Los spies pueden configurarse para responder de diferentes
maneras cuando son invocados:
Spies - Comportamiento
// spies on AND calls the original function spied on
spyOn(x, 'method').andCallThrough()
Los spies pueden configurarse para responder de diferentes
maneras cuando son invocados:
Spies - Comportamiento
// spies on AND calls the original function spied on
spyOn(x, 'method').andCallThrough()
// returns passed arguments when spy is called
spyOn(x, 'method').andReturn(arguments)
Los spies pueden configurarse para responder de diferentes
maneras cuando son invocados:
Spies - Comportamiento
// spies on AND calls the original function spied on
spyOn(x, 'method').andCallThrough()
// returns passed arguments when spy is called
spyOn(x, 'method').andReturn(arguments)
// throws passed exception when spy is called
spyOn(x, 'method').andThrow(exception)
Los spies pueden configurarse para responder de diferentes
maneras cuando son invocados:
Spies - Comportamiento
// spies on AND calls the original function spied on
spyOn(x, 'method').andCallThrough()
// returns passed arguments when spy is called
spyOn(x, 'method').andReturn(arguments)
// throws passed exception when spy is called
spyOn(x, 'method').andThrow(exception)
// calls passed function when spy is called
spyOn(x, 'method').andCallFake(function)
Los spies pueden configurarse para responder de diferentes
maneras cuando son invocados:
Spies - Matchers y propiedades
expect(x.method).toHaveBeenCalled()
expect(x.method).toHaveBeenCalledWith(args)
matchers
Spies - Matchers y propiedades
callCount
mostRecentCall.args
argsForCall[i]
expect(x.method).toHaveBeenCalled()
expect(x.method).toHaveBeenCalledWith(args)
matchers
propiedades
Spies - Matchers y propiedades
callCount
mostRecentCall.args
argsForCall[i]
expect(x.method.callCount).toEqual(1)
expect(x.method).toHaveBeenCalled()
expect(x.method).toHaveBeenCalledWith(args)
matchers
propiedades
Ajax - Ejemplo
Player.prototype.getNewSongs = function() {
var _this = this;
$.ajax({
url: '/songs',
dataType: 'json',
success: function(data) {
_this.displaySongs(data.songs);
},
error: function(data) {
_this.displayErrorMessage();
}
});
}
Ajax - Ejemplo
it('displays songs if getNewSongs is successful', function() {
var player = new Player();
spyOn($, 'ajax').andCallFake(function(e) {
e.success({songs: ['Some']});
});
spyOn(player, 'displaysSongs');
player.getNewSongs();
expect(player.displaySongs).toHaveBeenCalledWith(['Some']);
});
Mocking JavaScript Clock
beforeEach(function() {
timerCallback = jasmine.createSpy('timerCallback');
jasmine.Clock.useMock();
});
it('causes a timeout to be called synchronously', function() {
setTimeout(function() { timerCallback(); }, 100);
expect(timerCallback).not.toHaveBeenCalled();
jasmine.Clock.tick(101);
expect(timerCallback).toHaveBeenCalled();
});
Asynchronous Support
var foo = 0;
it('should be an async test', function() {
runs(function() {
setTimeout(function() { foo++ }, 250);
});
waits(500);
runs(function() {
expect(foo).toEqual(1);
});
});
jasmine-jquery
custom matchers para usar con jquery
expect($('<div id="some-id"></div>')).toBe('div')
var $div = $('<div><span class="a-class"></span></div>')
expect($div).toContain('span.a-class')
var $div = $('<div><h1>header</h1></div>')
expect($div).toContainText('header')
jasmine-jquery
loadFixtures('my_fixture.html');
manejo de fixtures html, css y json
loadStyleFixtures('my_fixture.css');
var data = getJSONFixture('my_json_fixture.json');
jasmine-jquery - Ejemplo
<div id="player-content">some complex content</div>
loadFixtures('player_fixture.html');
player.init();
expect($('#player-content')).to...;
player_fixture.html
Para tener en cuenta...
jasmine gem
https://github.com/pivotal/jasmine-gem
browser + rake task
sinon.js
http://sinonjs.org/
Fake XMLHttpRequest, Fake Server
try jasmine
http://tryjasmine.com/
Preguntas?

Más contenido relacionado

Destacado

Kohēzijas politikas ES fondu investīciju progress līdz 2014.gada 31.janvārim
Kohēzijas politikas ES fondu investīciju progress līdz 2014.gada 31.janvārimKohēzijas politikas ES fondu investīciju progress līdz 2014.gada 31.janvārim
Kohēzijas politikas ES fondu investīciju progress līdz 2014.gada 31.janvārimFinanšu ministrija
 
COMPARATIVE STUDY FOR PERFORMANCE ANALYSIS OF VOIP CODECS OVER WLAN IN NONMOB...
COMPARATIVE STUDY FOR PERFORMANCE ANALYSIS OF VOIP CODECS OVER WLAN IN NONMOB...COMPARATIVE STUDY FOR PERFORMANCE ANALYSIS OF VOIP CODECS OVER WLAN IN NONMOB...
COMPARATIVE STUDY FOR PERFORMANCE ANALYSIS OF VOIP CODECS OVER WLAN IN NONMOB...Zac Darcy
 
Will indian markets rise with modi?
Will indian markets rise with modi?Will indian markets rise with modi?
Will indian markets rise with modi?Deena Zaidi
 
Nieuwe financieringswijzer
Nieuwe financieringswijzerNieuwe financieringswijzer
Nieuwe financieringswijzerMastermate
 
A novel soa for e city with the increase of citizens participation approach
A novel soa for e city with the increase of citizens participation approachA novel soa for e city with the increase of citizens participation approach
A novel soa for e city with the increase of citizens participation approachZac Darcy
 
Math align in ConTeXt
Math align in ConTeXt Math align in ConTeXt
Math align in ConTeXt Hirwanto Iwan
 
Transforming earth into a paradise – part 4
Transforming earth into a paradise – part 4Transforming earth into a paradise – part 4
Transforming earth into a paradise – part 4Sabry Shaheen
 
Tomar Decisiones... Entre la Incertidumbre y la Asertividad
Tomar Decisiones... Entre la Incertidumbre y la AsertividadTomar Decisiones... Entre la Incertidumbre y la Asertividad
Tomar Decisiones... Entre la Incertidumbre y la AsertividadMaría Clara Ruiz Martínez
 
Thirsty for the truth book summary
Thirsty for the truth   book summaryThirsty for the truth   book summary
Thirsty for the truth book summarySabry Shaheen
 
Kultura1
Kultura1Kultura1
Kultura1krizma
 
The religion teacher by sabry shaheen - summary
The religion teacher   by sabry shaheen - summaryThe religion teacher   by sabry shaheen - summary
The religion teacher by sabry shaheen - summarySabry Shaheen
 
Mastermail - voorjaar 2015
Mastermail - voorjaar 2015Mastermail - voorjaar 2015
Mastermail - voorjaar 2015Mastermate
 

Destacado (17)

Kohēzijas politikas ES fondu investīciju progress līdz 2014.gada 31.janvārim
Kohēzijas politikas ES fondu investīciju progress līdz 2014.gada 31.janvārimKohēzijas politikas ES fondu investīciju progress līdz 2014.gada 31.janvārim
Kohēzijas politikas ES fondu investīciju progress līdz 2014.gada 31.janvārim
 
Three ads
Three adsThree ads
Three ads
 
Pleno Dementia
Pleno DementiaPleno Dementia
Pleno Dementia
 
COMPARATIVE STUDY FOR PERFORMANCE ANALYSIS OF VOIP CODECS OVER WLAN IN NONMOB...
COMPARATIVE STUDY FOR PERFORMANCE ANALYSIS OF VOIP CODECS OVER WLAN IN NONMOB...COMPARATIVE STUDY FOR PERFORMANCE ANALYSIS OF VOIP CODECS OVER WLAN IN NONMOB...
COMPARATIVE STUDY FOR PERFORMANCE ANALYSIS OF VOIP CODECS OVER WLAN IN NONMOB...
 
Will indian markets rise with modi?
Will indian markets rise with modi?Will indian markets rise with modi?
Will indian markets rise with modi?
 
Nieuwe financieringswijzer
Nieuwe financieringswijzerNieuwe financieringswijzer
Nieuwe financieringswijzer
 
A novel soa for e city with the increase of citizens participation approach
A novel soa for e city with the increase of citizens participation approachA novel soa for e city with the increase of citizens participation approach
A novel soa for e city with the increase of citizens participation approach
 
Math align in ConTeXt
Math align in ConTeXt Math align in ConTeXt
Math align in ConTeXt
 
Pavliuk final
Pavliuk finalPavliuk final
Pavliuk final
 
Transforming earth into a paradise – part 4
Transforming earth into a paradise – part 4Transforming earth into a paradise – part 4
Transforming earth into a paradise – part 4
 
Tomar Decisiones... Entre la Incertidumbre y la Asertividad
Tomar Decisiones... Entre la Incertidumbre y la AsertividadTomar Decisiones... Entre la Incertidumbre y la Asertividad
Tomar Decisiones... Entre la Incertidumbre y la Asertividad
 
Thirsty for the truth book summary
Thirsty for the truth   book summaryThirsty for the truth   book summary
Thirsty for the truth book summary
 
Kultura1
Kultura1Kultura1
Kultura1
 
The religion teacher by sabry shaheen - summary
The religion teacher   by sabry shaheen - summaryThe religion teacher   by sabry shaheen - summary
The religion teacher by sabry shaheen - summary
 
Mastermail - voorjaar 2015
Mastermail - voorjaar 2015Mastermail - voorjaar 2015
Mastermail - voorjaar 2015
 
4+5 шагов
4+5 шагов4+5 шагов
4+5 шагов
 
DISCOVER MIKE
DISCOVER MIKEDISCOVER MIKE
DISCOVER MIKE
 

Jasmine