Writing clean JavaScript tests using Jasmine. An introduction to Jasmine with some examples. Download the examples at http://github.com/michaelphines/Jasmine-Examples
The images are properly licensed and property of their respective owners. Please do not reuse.
You are free to use the source code samples however you like as long as it's not for absolute world domination.
4. It looks and feels like RSpec
describe "groups" do
before(:each) do
# Stuff to prepare for each spec
end
it "has expectations" do describe('appearance', function() {
# ... beforeEach(function() {
value.should == true // Stuff to prepare foe each spec
end });
end
it('has expectations', function() {
// ...
expect(value).toEqual(true);
});
}
10. Making it a little more complicated
function Greeter() {
this.sayHello = function() {
describe('Greeter', function() { return "Hello, World!";
var greeter; };
beforeEach(function() { this.sayGoodnight = function() {
greeter = new Greeter(); return "Goodnight, Moon!";
}); };
}
it('says hello', function() {
expect(greeter.sayHello()).toEqual("Hello, World!");
});
it('says goodnight', function() {
expect(greeter.sayGoodnight()).toEqual("Goodnight, Moon!");
});
});
11. Your Little Spies
(scribbled out the truth with their lies)
function Greeter(name) {
this.name = name;
this.getName = function() { return name; };
this.sayHello = function() {
return "Hello, " + this.getName() + "!";
};
}
// ...
it('uses the name', function() {
spyOn(greeter, 'getName').andReturn('name');
expect(greeter.sayHello()).toMatch(/name/);
expect(greeter.getName).wasCalled();
});
// ...
12. Lots of cool stuff to do with spies
• .andCallThrough()
• .andReturn(value)
Lets you spy on whether a function was called without
Stub out the function with a return value
having to stub it out
• .andCallFake(function) • .wasCalledWith(arguments)
Check whether a spy was called with certain arguments
Stub a function out by defining a replacement function
• .andThrow(message) • jasmine.createSpy(name)
Create a new object and spy on it as a mock
Immediately throw an exception when called
13. Fixtures!
describe('copyToDiv()', function() {
it('copies input data to content', function() {
JazzMoney.loadFixture("fixture");
copyToDiv();
var content = document.getElementById('content').innerHTML
expect(content).toEqual('source data');
});
});
function copyToDiv() {
var source = document.getElementById('source');
var content = document.getElementById('content');
content.innerHTML = source.innerHTML;
}
<div id="source">source data</div>
<div id="content"></div>