首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Sinon.js并阻止对我的应用服务器的调用

使用Sinon.js并阻止对我的应用服务器的调用
EN

Stack Overflow用户
提问于 2012-06-11 01:57:12
回答 1查看 2.1K关注 0票数 4

很简单的问题:

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

  1. 我不想真正点击服务器
  2. ,我想模拟来自服务器

的响应

这是JS:

代码语言:javascript
运行
复制
  $.ajax
    url: "/tickets/id.json"
    dataType: 'json'

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

这是我的测试:

代码语言:javascript
运行
复制
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( {})  

此测试失败,但有以下例外:

代码语言:javascript
运行
复制
TypeError: ajax expected to yield to 'done', but no object with such a property was passed. Received [[object Object]]

因此,我想我想知道我是否可以模拟一个jQuery请求来获得一个能够成功响应.done调用的响应,显然我对defferedObject()的理解不够好。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-26 11:44:53

要模拟服务器的响应,需要对$.ajax的返回值进行存根

代码语言:javascript
运行
复制
  ...
  @jquery_stub = sinon.stub(jQuery, 'ajax').returns
    done: (callback) -> callback {...} # your object here
  ...

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

还可以返回实际的jQuery延迟对象:

代码语言:javascript
运行
复制
  ...    
  @deferred = new jQuery.Deferred
  @jquery_stub = sinon.stub(jQuery, 'ajax').returns(deferred)
  ...

在这种情况下,您必须在执行测试之前显式地触发返回的延迟:

代码语言:javascript
运行
复制
  ...    
  @deferred.resolveWith(null, [{}]) # your object here
  ...
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10973839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档