weixin_33744141 2012-11-28 12:12 采纳率: 0%
浏览 39

测试Ajax茉莉花Sinon

describe('Ajax', function () {
  beforeEach(function () {
    // Instantiate module and reference it with this.testUser
    this.testUser = new TestUser();
    // Reference sinon.spy with this.spySetToken
    this.spySetToken = sinon.spy(this.testUser, 'setToken');
  });
  afterEach(function () {
    this.spySetToken.restore();
  });
  it('Does it respond with that data', function () {
    // Wrap $.ajax method and invoke success callback from ajax passing it a 'string'.
    sinon.stub($, 'ajax').yieldsTo('success', 'Custom response string');
    // test to see if my method that's inside the success callback is called with the string
    expect(this.spySetToken.toHaveBeenCalledWith('Custom response string');
  });

});

I'm getting 'Expected Function to be called'.

How do I test Ajax success methods successfully?

  • 写回答

1条回答 默认 最新

  • csdn产品小助手 2012-12-04 11:11
    关注

    Well I would have used sinon.fakeServer before but I didn't realise that it triggers the success of the original ajax call.

    So the solution was to do this:

    beforeEach(function () {
      var server = sinon.fakeServer.create();
      this.server.respondWith(
        "GET",
        "/the/url" // This should marry up to the url being tested i believe
        [200, {"Content-Type":"application/json"},
        '{response:"json"}']
      );
    };
    
    it('should set my model', function () {
      this.server.respond();
      expect(myModel.get('property').toEqual(');
    }
    

    Sinon.server will trigger the success of the ajax call in the feature so that you can test any functionality that you may have in the success method.

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题