0

我知道 Stackoverflow 中有很多关于这个的讨论,但我无法得到一个直接的答案。而且我对coffeescript知之甚少。

基本上,我有这个咖啡脚本

return42 = -> 42

当我编译时,我得到了这个


(function() {
  var return42;

  return42 = function() {
    return 42;
  };

}).call(this);

所以它被包裹在匿名函数中的函数,它没有暴露给世界。所以当我写这个测试


describe "Test number", ->
    it "is 42", ->
        expect(return42()).toBe 42

测试将失败,因为 return42() 未定义。我怎么能解决这个问题。

非常感谢你。:-)

4

2 回答 2

1

您需要一个全局变量作为程序的入口点。您可以通过将函数附加到全局对象而不是将其保留在函数的本地来实现这一点。试试这个:

@return42 = -> 42

这会给你:

(function() {
  this.return42 = function() {
    return 42;
  };
}).call(this);

If you are only running this in the browser and not Node.js, it would be a bit more idiomatic to attach to window instead of this, even though they are both the global object in this case.

于 2011-11-23T13:04:55.743 回答
0

While Jimmy is right, I would add that if you don't need to expose the function then you don't need to test it. Instead test the public APIs that use that function. So long as your public API depends on your private implementations, then the tests should fail if the private functions fail too.

于 2011-12-01T02:04:37.557 回答