Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript + Unit Testing : Global Variables?

I'm trying to use Jasmine for unit testing for a small application written in coffeescript. I've found many sources saying that unit testing can be done perfectly well on JS compiled from coffeescript. How do you access the data and logic of the JS code, if everything is wrapped in an anonymous function to avoid polluting the name space? Is the only solution to run the compiler with the -b flag every time?

like image 402
Jeff Avatar asked Apr 05 '11 07:04

Jeff


2 Answers

You should test against the public interface that you expose from your CoffeeScript module. If your module is called Foo and exposes two public methods, bar and baz, you might export them as follows:

Foo =
    bar: (a, b) ->
        #implementation
    baz: (c) ->
        #implementation
(exports ? this).Foo = Foo

There are other variations on this pattern, of course. See underscore.coffee, for example. Now that you have your public interface exposed, just make it available to your Jasmine tests in whatever way is appropriate. If you're using jasmine-node, for example, you would do the following:

Foo = require('foo') #assuming your module is compiled to foo.js

Your tests would then call Foo.bar and Foo.baz.

like image 104
lawnsea Avatar answered Sep 24 '22 02:09

lawnsea


There are very few cases where it makes sense to use -b; ordinary testing isn't one of them. lawnsea is quite correct that you should be exporting everything you test (attaching it to exports under Node, or window in a browser). It's the same as any programming language, really.

For Jasmine and CoffeeScript, especially in conjunction with jQuery, you should take a look at the InstantJasmineCoffee project and this related blog post.

like image 38
Trevor Burnham Avatar answered Sep 23 '22 02:09

Trevor Burnham