Skip to content

Instantly share code, notes, and snippets.

@plukevdh
Created May 15, 2014 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save plukevdh/d419f3a14f92e2cd023a to your computer and use it in GitHub Desktop.
Save plukevdh/d419f3a14f92e2cd023a to your computer and use it in GitHub Desktop.
TeachTDD example code
var Storage = (function() {
var uniqueId = 0;
function Storage() {}
Storage.prototype.add = function(item) {
var id = this.generateId()
, data = this._toJSON(item);
localStorage[id] = data;
};
Storage.prototype.generateId = function() {
return ++uniqueId;
};
Storage.prototype.reset = function() {
uniqueId = 0;
};
Storage.prototype._toJSON = function(items) {
return JSON.stringify(items);
};
Storage.prototype._fromJSON = function(json) {
return JSON.parse(json);
};
return Storage;
})();
window.Storage = Storage;
describe("Storage", function() {
var store;
beforeEach(function() {
store = new Storage();
store.reset();
});
it("can generate unique ids", function() {
var ids = [
store.generateId(),
store.generateId(),
store.generateId(),
store.generateId()
];
expect(ids).toEqual([1,2,3,4]);
});
it("can reset the id counter", function() {
store.generateId();
var last = store.generateId();
expect(last).toEqual(2);
store.reset();
last = store.generateId();
expect(last).toEqual(1);
});
it("can encode content", function(){
data = {one: 1, two: 2};
encoded = store._toJSON(data);
expect(encoded).toEqual('{"one":1,"two":2}');
});
it("can decode content", function(){
data = '{"one":1,"two":2}';
encoded = store._fromJSON(data);
expect(encoded).toEqual({one: 1, two: 2});
});
it("can store an item", function() {
var data = {item: "Test"};
store.add(data);
expect(localStorage[1]).toEqual(JSON.stringify(data));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment