10. Before y after
describe("A spec (with setup and tear-down)", function() {
var foo;
beforeEach(function() {
foo = 0;
foo += 1;
});
afterEach(function() {
foo = 0;
});
it("is just a function, so it can contain any code", function() {
expect(foo).toEqual(1);
});
it("can have more than one expectation", function() {
expect(foo).toEqual(1);
expect(true).toEqual(true);
});
});
11. Spies
var Person = function() {};
Person.prototype.helloSomeone = function(toGreet) {
return this.sayHello() + " " + toGreet;
};
Person.prototype.sayHello = function() {
return "Hello";
};
describe("Person", function() {
it("calls the sayHello() function", function() {
var fakePerson = new Person();
spyOn(fakePerson, "sayHello");
fakePerson.helloSomeone("world");
expect(fakePerson.sayHello).toHaveBeenCalled();
});
});
13. Tests asincronos(run(),waitsFor())
describe("Calculator", function() {
it("should factor two huge numbers asynchronously", function() {
var calc = new Calculator();
var answer = calc.factor(18973547201226, 28460320801839);
expect(answer).toEqual(9486773600613); // DANGER ZONE:
This doesn't work if factor() is asynchronous!!
// THIS DOESN'T WORK, STUPID
});
});
14. Tests asincronos(run(),waitsFor())
describe("Calculator", function() {
it("should factor two huge numbers asynchronously", function() {
var calc = new Calculator();
var answer = calc.factor(18973547201226, 28460320801839);
waitsFor(function() {
return calc.answerHasBeenCalculated();
}, "It took too long to find those factors.", 10000);
runs(function() {
expect(answer).toEqual(9486773600613);
});
});
});
15. Tests jQuery
describe('I add a ToDo', function () {
var mocks = {};
beforeEach(function () {
loadFixtures("index.html");
mocks.todo = "something fun";
$('#todo').val(mocks.todo);
ToDo.setup();
});
it('should call the addToDo function when create is clicked', function () {
spyOn(ToDo, 'addToDo');
$('#create').click();
expect(ToDo.addToDo).toHaveBeenCalledWith(mocks.todo);
});
});
16. Referencias
Pivotal Labs pagina oficial
http://pivotal.github.com/jasmine/
How do I Jasmine
http://evanhahn.com/?p=181
jasmine-jquery
https://github.com/velesin/jasmine-jquery/
Testing jQuery plugins with Node.js and Jasmine
http://digitalbush.com/2011/03/29/testing-jquery-plugins-
with-node-js-and-jasmine/
Tests de JavaScript con Jasmine
http://es.asciicasts.com/episodes/261-tests-de-
javascript-con-jasmine