首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试ajax jasmine sinon

测试ajax jasmine sinon
EN

Stack Overflow用户
提问于 2012-11-28 20:12:44
回答 1查看 590关注 0票数 1
代码语言:javascript
复制
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');
  });

});

我得到了“期望被调用的函数”。

如何成功测试Ajax成功方法?

EN

回答 1

Stack Overflow用户

发布于 2012-12-04 19:11:23

我以前可能会使用sinon.fakeServer,但我没有意识到它会触发最初的ajax调用的成功。

因此,解决方案是这样做:

代码语言:javascript
复制
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将触发特性中的ajax调用的成功,以便您可以测试成功方法中可能具有的任何功能。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13604816

复制
相关文章

相似问题

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