2012-02-20 75 views
4

我試圖用Sinon.js來模擬服務器對POST請求的響應。它似乎工作正常,除非不成功回調。Sinon.js fakeServer沒有用響應方法觸發回調

# In the Exercise model: 

    submit: (query) -> 
    callback = (data) -> alert(data) 
    $.post(@url(), { query: query }, callback) 

# In the Exercise spec: 

    beforeEach -> 
    @server = sinon.fakeServer.create() 
    @server.respondWith('POST', @exercise.url(), 
         [ 200, { "Content-Type": "application/json" }, 
         '[{ correct: true, result_set: {} }' ]) 

    @exercise.submit('select * from students') 


    # passes 
    it "request is a POST", -> 
    expect(@server.requests[0].method).toEqual('POST') 

    # passes 
    it "submits to the correct url", -> 
    expect(@server.requests[0].url).toEqual(@exercise.url()) 

    it "fires the callback", -> 
    @server.respond() 
    # no callback fired! but if I inspect the server object I can see that 
    # the queue is empty, and the response is properly attached to the request object. 
    # see the state below 

# State of the Server object 

{"requests":[ 
{"readyState":4, 
"requestHeaders": 
    {"Content-Type":"application/x-www-form-urlencoded;charset=utf-8", 
    "Accept":"*/*", 
    "X-Requested-With":"XMLHttpRequest"}, 
"requestBody":"query=select+*+from+students", 
"status":200, 
"statusText":"OK", 
"method":"POST", 
"url":"exercises/some_id", 
"async":true, 
"responseText":"[ 
    { correct: true, 
     result_set: 
     {} }", 
"responseXML":null, 
"sendFlag":true, 
"errorFlag":false, 
"responseHeaders": 
    {"Content-Type":"application/json"}}], 
"responses":[ 
{"method":"POST", 
"url":"exercises/some_id", 
"response":[200, 
    {"Content-Type":"application/json"},"[ 
    { correct: true, 
     result_set: 
     {} }"]}], 
    "queue":[]} 

回答

4

它觸發錯誤回調,因爲你的JSON是無效的:'[{ correct: true, result_set: {} }'嘗試使用http://jsonlint.com/驗證您的答覆,或使用JSON.stringify,那麼你就不需要擔心。

+0

好眼睛基督徒!在JSON解析錯誤的情況下,我會預期在某處出現錯誤。謝謝。 – brentvatne 2012-02-20 08:12:03

+0

好吧,錯誤回調中出現錯誤;)Sinon大多不會試圖瞭解任何關於響應內容的內容,就像瀏覽器不會。 – 2012-02-20 10:05:11