Dojo and doh: test for specific topic subscriptions

323 views Asked by At

Does anyone know a way to use doh to test if an object is subscribed to a specific topic?

I am struggling to find any docs desccribing this type of test.

The reason that I am asking this is becuase when I construct my widget I subscribe it to a topic. I wanted to have a unit test that tests if the widget always has that topic subscription after its construction.

My topic has a private variable that I use as the topic string when creating the subscription.

So for example here is a topic called "CustomTopic":

define([], function(){

    var topicString= "topicString";

    return {
        TOPIC_STRING: function(){
            return topicString;
        }
    }
})

and the constructor in my widget looks like:

constructor: function() {   
    topic.subscribe(CustomTopic.TOPIC_STRING(), function(params) {doSomething(params)});
}

So you can see how easy it would be to check for the topic subscription against the private variable value, if I could just figure out how to see all subscriptions my widget has?

For reference:

Dojo 1.8 docs

Dojo's test util "doh" docs

1

There are 1 answers

3
Frances McMullin On

I suggest your testing will be more robust / useful if it concentrates on behaviour as opposed to implementation. In this case, it would make more sense to test if your widget responds to the topic (or better still, the event that causes the topic to be published, for more of an integration test) rather than attempting to catch the subscription itself.

Of course, you could try and wrap topic.subscribe (bad thing), or inspect your widget's private list of handles (another bad thing). Incidentally, I hope you are in fact saving the handle returned by topic.subscribe so that you can remove (previously, unsubscribe) it later when the object is destroyed.

Better than those would be to simply make a new object, publish to that topic, and see if doSomething is called, or if the desired result has occurred. While doh does not provide support for listening to function calls, dojo/aspect is ideal for this purpose. So you might have something like this :

var myWidget = new myWidget(); // presumably subscription happened, 
                               // but we only care about later behaviour
var somethingDone = false;
aspect.after(window, "doSomething", function(){somethingDone = true;});
topic.publish(CustomTopic.TOPIC_STRING());
doh.assertTrue(somethingDone);

In fact, I assume doSomething is not a global method, so you'll have to scope that properly, but otherwise this should work fine. Currently topic.publish is synchronous, so this should work fine, but it could become async in the future, in which case you would want to avoid calling doh.assertTrue until some later stage.