我正在尝试使用Sinon.js模拟POST
请求的服务器响应。它似乎工作正常,但不会触发成功回调。
# 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":[]}
答案 0 :(得分:4)
它会触发错误回调,因为您的JSON无效:'[{ correct: true, result_set: {} }'
尝试使用http://jsonlint.com/验证您的回复,或使用JSON.stringify
,然后您无需担心。