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

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

问题描述

我正在尝试使用 Jasmine 对一个用咖啡脚本编写的小型应用程序进行单元测试.我发现许多消息来源说单元测试可以在从咖啡脚本编译的 JS 上完美完成.如果所有内容都包装在匿名函数中以避免污染名称空间,您如何访问 JS 代码的数据和逻辑?是每次都使用 -b 标志运行编译器的唯一解决方案吗?

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?

推荐答案

您应该针对您从 CoffeeScript 模块公开的公共接口进行测试.如果您的模块名为 Foo 并公开了两个公共方法 barbaz,您可以按如下方式导出它们:

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

当然,这种模式还有其他变体.例如,参见 underscore.coffee.现在您已经公开了公共接口,只需以适当的方式将其提供给您的 Jasmine 测试即可.例如,如果您使用 jasmine-node,您将执行以下操作:

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

然后您的测试将调用 Foo.barFoo.baz.

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

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

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