【问题标题】:Coffescript testing catch ajax callsCoffeescript 测试捕获 ajax 调用
【发布时间】:2014-05-14 16:52:47
【问题描述】:

我正在尝试测试来咖啡脚本类,但我遇到了 ajax 调用问题。例如在咖啡中,我使用 $.getJSON 从服务器获取一些数据。如何在我的测试中捕获此请求或重定向到某个假服务器?我读过一些关于 sinon fakeServer 的文章,我尝试过这样的事情:

describe "TestClass", ->
  describe "#run", ->
    beforeEach ->
      url     = "/someUrl'
      @server = sinon.fakeServer.create()

      $ =>
        @server.respondWith("GET", url,
         [200, {"Content-Type": "application/json"},
                                    '{}'])

      @entriesDownloader = new TestClass().run()

但它不起作用。在方法运行中,我使用 jquery 调用 API。如何捕捉这个请求并返回一些模拟。谢谢大家的回答。

【问题讨论】:

    标签: testing coffeescript sinon


    【解决方案1】:

    您可以只存根$.getJSON 方法,而不需要假服务器。例如:

    sinon.stub($, 'getJSON').yields({ prop: 'val' });
    

    或者,如果您只想为某些 url 存根行为:

    sinon.stub($, 'getJSON').withArgs('/someUrl').yields({ prop: 'val' });
    

    该方法可以使用$.getJSON.restore()随时恢复

    【讨论】:

      【解决方案2】:

      在我看来,您好像缺少回调间谍。而且您似乎没有运行任何测试,只是 beforeEach。这是文档中的示例,它遵循 AAA 的典型模式:Arrange、Act、Assert:

      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
      

      assert callback.calledOnce 非常重要。另一个方便的函数是calledWith,就像这样:callback.calledWith(1, 2, 3)。当您将一组已知的参数传递给测试函数时,使用它来确保您的代码将正确的参数传递给外部函数。

      【讨论】:

        猜你喜欢
        • 2018-05-31
        • 2022-09-23
        • 2012-05-09
        • 1970-01-01
        • 2015-02-18
        • 1970-01-01
        • 2014-05-21
        • 2013-07-06
        • 2011-03-08
        相关资源
        最近更新 更多