【问题标题】:Testing ajax jasmine sinon测试ajax jasmine sinon
【发布时间】:2012-11-28 12:12:44
【问题描述】:
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 成功方法?

【问题讨论】:

  • 好吧,您的测试似乎没有进行任何 Ajax 调用(您只是在设置间谍)。你确定你没有丢失代码?

标签: ajax jasmine sinon


【解决方案1】:

好吧,我之前会使用 sinon.fakeServer,但我没有意识到它会触发原始 ajax 调用的成功。

所以解决方案是这样做:

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 调用成功,以便您可以测试成功方法中可能具有的任何功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 2014-12-27
    • 2013-03-17
    • 2017-06-20
    • 2012-10-20
    • 1970-01-01
    相关资源
    最近更新 更多