jquery - 使用 Sinon.js 并阻止调用我的应用程序服务器

标签 jquery coffeescript jquery-deferred sinon

足够简单的问题:

我希望 sinon.js 测试一段 javascript,以确保它在执行以下两件事时调用 $.ajax 方法:

  1. 我不想真正访问服务器
  2. 我想模拟来自服务器的响应

这是 JS:

  $.ajax
    url: "/tickets/id.json"
    dataType: 'json'

  .done (data) =>
    HandlebarsTemplates["tickets/popup_title"] data

这是我的测试:

describe 'PopupDisplayer', ->

  beforeEach ->
    loadFixtures 'popup_displayer'
    new PopupDisplayer

    @title_stub = sinon.stub( HandlebarsTemplates, "tickets/popup_title")

    @jquery_stub = sinon.stub(jQuery, 'ajax').yieldsTo('done', {})

    //This triggers the ajax call
    $('.popupable .title').mouseenter()

  afterEach ->
    HandlebarsTemplates['tickets/popup_title'].restore()
    HandlebarsTemplates['tickets/popup_content'].restore()

    jQuery.ajax.restore()

    @server.restore()

  it 'renders the title with the data returned from the server', ->
    expect(@title_stub).toHaveBeenCalledWith( {})  

此测试失败,但有以下异常(exception):

TypeError: ajax expected to yield to 'done', but no object with such a property was passed. Received [[object Object]]

所以我想我想知道是否可以模拟一个 jQuery 请求来获得可以成功响应 .done 调用的响应,显然我不理解 deferedObject( ) 足够了。

最佳答案

要模拟服务器的响应,您需要 stub $.ajax 的返回值:

  ...
  @jquery_stub = sinon.stub(jQuery, 'ajax').returns
    done: (callback) -> callback {...} # your object here
  ...

请注意,这只会 stub done 回调。如果您想测试其他行为,您可能需要实现其他处理程序(failthen 等)。

您还可以返回一个实际的 jQuery Deferred 对象:

  ...    
  @deferred = new jQuery.Deferred
  @jquery_stub = sinon.stub(jQuery, 'ajax').returns(deferred)
  ...

在这种情况下,您必须在进行测试之前显式触发返回的 Deferred:

  ...    
  @deferred.resolveWith(null, [{}]) # your object here
  ...

关于jquery - 使用 Sinon.js 并阻止调用我的应用程序服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10973839/

相关文章:

容器中的 JQuery 选择选择框溢出 : hidden

jquery - 基于名称的黑白插件和基于功能的插件的区别

javascript - 无需在d3.js中使用selectAll即可忽略第一个数据

javascript - 如何在JS/jQuery中创建不同的交互模式?

javascript - coffeescript 中的单例类

javascript - 忽略 jQuery.when 期间的超时

django - 如何在 Django 项目中使用 CoffeeScript ?

javascript - Coffeescript:使用 coffeescript 的 moment js 动态更新时间

jquery - 我可以在 document.ready() 上获得 jQuery Deferred 吗?

jquery - 使用新的 jQuery 1.6 $.animate "promise"和回调之间的区别?