Coffeescript +单元测试:全局变量? [英] Coffeescript + Unit Testing : Global Variables?

查看:119
本文介绍了Coffeescript +单元测试:全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Jasmine进行单元测试的小型应用程序用coffeescript。我发现很多来源说单元测试可以完美地完成从JS编译的coffeescript。如何访问JS代码的数据和逻辑,如果一切都包装在匿名函数中,以避免污染名称空间?是每次都用-b标志运行编译器的唯一解决方案?

解决方案

从您的CoffeeScript模块暴露。如果你的模块被调用 Foo 并暴露两个公共方法, bar baz ,您可以如下导出它们:

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

当然,这种模式的其他变化。例如,请参见 underscore.coffee 。现在,你的公共接口暴露,只要使其可用于您的Jasmine测试以任何适当的方式。例如,如果您使用茉莉花节点,您将执行以下操作:

  Foo = require('foo') #assuming你的模块被编译为foo.js 

然后你的测试会调用 Foo.bar Foo.baz


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?

解决方案

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.

这篇关于Coffeescript +单元测试:全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆