Coffeescript类中的方法返回函数而不是字符串

时间:2015-02-11 12:16:59

标签: javascript meteor coffeescript jasmine

我只是想调用一个函数,该函数从动态构建的继承类返回一个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的新手。

谢谢!

1 个答案:

答案 0 :(得分:2)

下面

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

您想在超类中调用方法baseUrl,而只是引用它。那么函数本身就会得到toString ed和" news / articles"附加。这会产生字符串:function () { return "http://api" + (this.getVersion()) + ".mysite.com/api/" + (this.getVersion()) + "/"; }news/articles,这是您在测试错误中看到的。

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

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

然后,您可以删除无用的toString电话。

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

相关问题