Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Created February 20, 2015 12:57
Show Gist options
  • Save jarrettmeyer/2639c4f58044c96baead to your computer and use it in GitHub Desktop.
Save jarrettmeyer/2639c4f58044c96baead to your computer and use it in GitHub Desktop.
Singleton Tests
var assert = require('assert');
describe('how not to make a singleton', function () {
var a, b;
beforeEach(function () {
a = { message: "Hello, World!" };
b = { message: "Hello, World!" };
});
it('says matching strings are equal', function () {
assert.ok(a.message === b.message);
});
it('says different objects are different', function () {
assert.equal(a === b, false);
});
});
describe('how to make a singleton', function () {
function Builder() {
this.instance = null;
}
Builder.prototype.build = function () {
if (!this.instance) {
this.instance = { message: "Hello, World!" };
}
return this.instance;
};
it('creates the same instance with a builder', function () {
var builder = new Builder();
var a = builder.build();
var b = builder.build();
assert.equal(a === b, true);
});
it('does not create the same instance if you make two builders', function () {
var a = new Builder().build();
var b = new Builder().build();
assert.equal(a === b, false);
});
it('modifies the two objects together', function () {
var builder = new Builder();
var a = builder.build();
var b = builder.build();
a.value = 123;
assert.equal(b.value, 123);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment