Unit testing callbacks with YUI.test

February 12, 2011

I came across a small problem with unit testing functions which take a callback. If you write your test like this:

"should callback with error on connection failed": function () {
  thing.doSomething(function(result) {
    Y.Assert.areEqual(result, "error");
  });
},

That test will pass even when the callback is never called. Your code could silently swallow errors, but your test would always pass. The assert never gets called.

If you write the test like this instead:

"should callback with error on connection failed": function () {
  var result;
  thing.doSomething(function(res) {
    result = res;
  });
  Y.Assert.areEqual(result, "error");
},

This will mean that your assert will always get called. You may run into problems if the doSomething function calls something asynchronous – but that’s where dependency injection and mocking can help you.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: