Test a singlton

26 views
Skip to first unread message

Ruben Oliveira

unread,
May 18, 2013, 12:07:18 PM5/18/13
to js-test...@googlegroups.com
Hi,

I have the need to test an object witch is a singleton like this:

==
file: singleton.js

(function() {

function Singleton() {

var currentState = 1;

this.setState = function(newState) {
currentstate = newState;
}
}

window.mySingleton = new Singleton();
})()
== 

The problem is in each test I want a fresh singleton. If this wasn't a singleton I could just use the setUp() method to instanciate a new object. But in this case, I can not do that, and window.mySingleton's state depends on the test that run before.

Any suggestions?

Thanks!

Cory Smith

unread,
May 18, 2013, 2:57:13 PM5/18/13
to JsTestDriver
Yes.

Don't put state in a singleton.

Seriously.

Otherwise, you'll need a method to reset the singleton state in tearDown.


--
You received this message because you are subscribed to the Google Groups "JsTestDriver" group.
To unsubscribe from this group and stop receiving emails from it, send an email to js-test-drive...@googlegroups.com.
To post to this group, send email to js-test...@googlegroups.com.
Visit this group at http://groups.google.com/group/js-test-driver?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Ruben Oliveira

unread,
May 19, 2013, 5:55:21 AM5/19/13
to js-test...@googlegroups.com
Hi Cory,

I understand what you mean. But the code is just an example. In the project I'm working on, the singleton is a manager, that receives instances of other classes (singletons too, by the way). Something like this:

manager.js
==
(function() {

function Manager() {

var managedInstances = [];

this.loadInstance = function(instance) {
managedInstances.push(instance);
}

}

window.myManager = new Manager();
})()
==

What you mean is that the manager shouldn't be a singleton? But there is no need to have more than an instance of it...

Igor Minar

unread,
May 21, 2013, 1:05:33 PM5/21/13
to js-test...@googlegroups.com

window.mySingleton = new Singleton();

if you ever do this in your code then this single line of code made your code untestable.

instead, you should decouple the Singleton instantiation from its definition. The definition should remain in your singleton.js file, while the instantiation should be part of your application bootstrap code.

even better: use a dependency injection library instead of writing your own bootstrap code. AngularJS has a nice DI and there is a new one being brewed at https://github.com/IgorMinar/di.js

/i

Reply all
Reply to author
Forward
0 new messages