类初始化总是失败

时间:2012-11-09 05:33:48

标签: javascript ajax coffeescript jasmine

我是JavaScript的新手,并使用CoffeeScript学习。我想创建一个类,在初始化时使用Ajax与 Flickr Web API 进行通信。

class Photo

  json: null

  constructor: ->
    @getJson()

  _getJson: (data) ->
    @json = data.photos.photo

  getJson: ->
    $.ajax(
      url : 'http://www.flickr.com/services/rest/'
      type : 'GET'
      data :
        format : 'json'
        method : 'flickr.photos.search'
        api_key : 'api_key'
        user_id : '29242822@N00'
        per_page : '100'
      dataType : 'jsonp'
      jsonp : 'jsoncallback'
      success : @_getJson
    )

我写了一个 Jasmine 测试来测试类的初始化。

describe("Photo", ->
  photo = new Photo
  console.log(photo.json)
  it("should get json when constructed", ->
    expect(photo.json).toBeDefined()
  )
  it("should have json which begins", ->
    expect(photo.json[0].title).beBe('Ridges of Shirouma')
  )
)

photo.json始终为空。

谢谢你的善意。

1 个答案:

答案 0 :(得分:1)

$.ajax在设置对象的上下文中调用其回调函数:

  

上下文对象

     

此对象将成为所有与Ajax相关的回调的上下文。默认情况下,上下文是一个对象,表示调用中使用的ajax设置($.ajaxSettings与传递给$.ajax的设置合并)。

所以@不是你的回调中的Photo对象,它是一些对你没用的设置对象。但是,如果您通过使用fat-arrow (=>)

定义_getJson来将_getJson: (data) => @json = data.photos.photo 绑定到您的照片上
@

然后@json将是您的照片,而{{1}}最终会成为您正在寻找的照片。

您可能遇到的下一个问题是,当Jasmine尝试查看它是否有效时,您的AJAX调用不一定会返回。我对Jasmine并不熟悉,但人们似乎喜欢this answer on testing AJAX with Jasmine;还有http://github.com/pivotal/jasmine-ajax用于存根AJAX部分以避免异步部分。