Skip to content

Instantly share code, notes, and snippets.

@dznz
Last active December 16, 2015 12:59
Show Gist options
  • Save dznz/5438732 to your computer and use it in GitHub Desktop.
Save dznz/5438732 to your computer and use it in GitHub Desktop.
Minor examples of Jasmine tests.
// collections/ScheduleDayCollectionSpec.js
describe("ScheduleDayCollection", function() {
var date;
var schedule_days;
beforeEach(function() {
date = "2012-07-10"
schedule_days = new wb.ScheduleDayCollection();
schedule_days.reset([{"id":"1", "date":date},{"id":"2", "date":"2012-07-11", "selected":"true"}]);
schedule_days.setSelected(date);
});
it("should be able to set selected", function() {
expect(schedule_days.at(0).get("selected")).toBeTruthy();
});
it("should unselect previously selected days", function() {
expect(schedule_days.at(1).get("selected")).toBeFalsy();
});
});
// jasmine_examples/PlayerSpec.js
describe("Player", function() {
var player;
var song;
beforeEach(function() {
player = new Player();
song = new Song();
});
it("should be able to play a Song", function() {
player.play(song);
expect(player.currentlyPlayingSong).toEqual(song);
//demonstrates use of custom matcher
expect(player).toBePlaying(song);
});
describe("when song has been paused", function() {
beforeEach(function() {
player.play(song);
player.pause();
});
it("should indicate that the song is currently paused", function() {
expect(player.isPlaying).toBeFalsy();
// demonstrates use of 'not' with a custom matcher
expect(player).not.toBePlaying(song);
});
it("should be possible to resume", function() {
player.resume();
expect(player.isPlaying).toBeTruthy();
expect(player.currentlyPlayingSong).toEqual(song);
});
});
// demonstrates use of spies to intercept and test method calls
it("tells the current song if the user has made it a favorite", function() {
spyOn(song, 'persistFavoriteStatus');
player.play(song);
player.makeFavorite();
expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true);
});
//demonstrates use of expected exceptions
describe("#resume", function() {
it("should throw an exception if song is already playing", function() {
player.play(song);
expect(function() {
player.resume();
}).toThrow("song is already playing");
});
});
});
// helpers/SpecHelper.js
beforeEach(function() {
this.addMatchers({
toBePlaying: function(expectedSong) {
var player = this.actual;
return player.currentlyPlayingSong === expectedSong
&& player.isPlaying;
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment