Testing Coffescript测试捕获ajax调用
我正在尝试测试comecoffeescript类,我对ajax调用有问题。例如,在coffee中,我使用$.getJSON从服务器获取一些数据。如何在测试中捕获此请求或重定向到某个假服务器?我读过一些关于sinon fakeServer的文章,我尝试了以下内容:Testing Coffescript测试捕获ajax调用,testing,coffeescript,sinon,Testing,Coffeescript,Sinon,我正在尝试测试comecoffeescript类,我对ajax调用有问题。例如,在coffee中,我使用$.getJSON从服务器获取一些数据。如何在测试中捕获此请求或重定向到某个假服务器?我读过一些关于sinon fakeServer的文章,我尝试了以下内容: describe "TestClass", -> describe "#run", -> beforeEach -> url = "/someUrl' @server = s
describe "TestClass", ->
describe "#run", ->
beforeEach ->
url = "/someUrl'
@server = sinon.fakeServer.create()
$ =>
@server.respondWith("GET", url,
[200, {"Content-Type": "application/json"},
'{}'])
@entriesDownloader = new TestClass().run()
但它不起作用。在方法run中,我使用jquery调用API。如何捕获此请求并返回一些模拟。谢谢你的回答。在我看来,你好像错过了回叫间谍。而且您似乎没有运行任何测试,只运行每个测试之前的
。这是文档中的示例,它遵循AAA的典型模式:安排、行动、断言:
server = undefined
before ->
server = sinon.fakeServer.create()
after ->
server.restore()
it "calls callback with deserialized data", ->
callback = sinon.spy()
getTodos 42, callback
server.requests[0].respond 200,
"Content-Type": "application/json"
, JSON.stringify([
id: 1
text: "Provide examples"
done: true
])
assert callback.calledOnce
断言callback.calledOnce是非常重要的。另一个方便的函数是
calledWith
,如下所示:callback.calledWith(1,2,3)
。当您将一组已知参数传递给测试函数时,使用该参数可以确保代码将正确的参数传递给外部函数 您可以只存根$.getJSON
方法,而不需要假服务器。例如:
sinon.stub($, 'getJSON').yields({ prop: 'val' });
或者,如果您只想为某些URL存根行为:
sinon.stub($, 'getJSON').withArgs('/someUrl').yields({ prop: 'val' });
使用$.getJSON.restore()