【问题标题】:Method in Coffeescript Class returns function instead of stringCoffeescript 类中的方法返回函数而不是字符串
【发布时间】:2015-04-11 19:30:54
【问题描述】:

我只是想调用一个函数,它从一个动态构建的继承类返回一个 Url 作为字符串:

class @Api

  DEFAULT_API_VERSION: 'v2'

  constructor: ->
    @setVersion(@DEFAULT_API_VERSION)
    return

  setVersion: (version) ->
    @version = version if version?

  getVersion: ->
    @version

  baseUrl: ->
    "http://api#{@getVersion()}.mysite.com/api/#{@getVersion()}/"

class @ApiArticle extends Api

  constructor: ->
    super
    return

  articlesUrl: ->
   "#{@baseUrl}news/articles".toString()

这是父类中的测试 PASSING

  it 'provides the baseUrl for Api calls', ->
     api = new Api()   
     expect(api.baseUrl()).toEqual('http://apiv2.mysite.com/api/v2/')

这是我的测试,它失败

it 'returns all news articles url', ->
  new ApiArticle()
  url = api_article.articlesUrl()
  expect(url).toEqual 'http://apiv2.mysite.com/api/v2/news/articles'

我从这个规范中得到的结果,它应该是一个字符串,但收到了这个:

 Expected
    'function () { return "http://api" + (this.getVersion()) + ".mysite.com/api/" + (this.getVersion()) + "/"; }news/articles'
 to equal
    'http://apiv2.mysite.com/api/v2/news/articles'.

有什么遗漏吗?我必须显式渲染/计算吗?

我对 JS 和 Coffee 很陌生。

谢谢!

【问题讨论】:

    标签: javascript meteor coffeescript jasmine


    【解决方案1】:

    这里

    articlesUrl: ->
        "#{@baseUrl}news/articles".toString()
    

    您想在超类中调用方法baseUrl,但您只引用了它。所以函数本身得到toStringed,并附加了“新闻/文章”。这会产生字符串:function () { return "http://api" + (this.getVersion()) + ".mysite.com/api/" + (this.getVersion()) + "/"; }news/articles,这就是您在测试错误中看到的内容。

    通过实际调用baseUrl 来修复它,而不仅仅是引用它:

    articlesUrl: ->
        "#{@baseUrl()}news/articles".toString()
    

    然后您可以删除无用的toString 调用。

    您可能需要考虑重命名方法getBaseUrl 以避免再次犯此错误。

    【讨论】:

    • 谢谢,它现在也可以在没有附加toString()的情况下使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多