开发者

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 开发者_Python百科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?


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.


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.


I just stumbled upon this, but if you're looking to get started with Jasmine + CoffeeScript on the cheap, you could check out this skeleton Sinatra app that I posted to Github. It uses a rack filter to compile the CoffeeScript dynamically. Example specs & instructions included: https://github.com/searls/jasmine-coffee

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜