如何使用 Jasmine BDD 创建 ajax 函数的存根

发布于 2024-12-27 05:12:05 字数 641 浏览 0 评论 0原文

我正在努力寻找有关如何使用 Jasmine BDD 伪造 ajax 调用的任何示例?

我有一个自定义的 ajax 函数,其工作原理如下...

ajax({
    url: 'JSON.php',
    dataType: 'json',           
    onSuccess: function(resp) {
        console.log(resp);
    }
});

...并且我不知道如何创建一个存根来伪造调用实际的 ajax 函数。

我想避免调用 ajax 函数,因为如果对服务器的真正 ajax 调用需要一些时间来响应,并且我的测试套件中有大量规格,那么它可能会减慢我的测试套件的速度。

我听说您可以使用 spyOn(namespace, 'ajax') 但这很烦人,因为它要求我将我的 ajax 函数包装在一个对象中只是为了使用 spyOn 函数(但无论如何我无法遵循,因为我找不到任何伪造 ajax 调用的具体示例)。

我还听说您可以使用 createSpy() ,但文档也不是很有帮助(GitHub 上相应的 wiki 也不是)。

任何解释如何使用间谍创建虚假 ajax 调用的帮助将不胜感激!

I'm struggling to find any examples on how to fake an ajax call using Jasmine BDD?

I have a custom ajax function that works like so...

ajax({
    url: 'JSON.php',
    dataType: 'json',           
    onSuccess: function(resp) {
        console.log(resp);
    }
});

...and I've no idea how to create a stub to fake calling the actual ajax function.

I want to avoid calling the ajax function as it could slow down my test suite if a real ajax call to the server takes some time to respond and I've loads of specs in my test suite.

I've heard that you can use spyOn(namespace, 'ajax') but that is annoying straight away as it requires me to wrap my ajax function in an object just to use the spyOn function (but regardless I wasn't able to follow along as I couldn't find any specific examples to fake an ajax call).

I've also heard that you can use createSpy() but again the documentation isn't very helpful (neither is the corresponding wiki on GitHub).

Any help explaining how to use spies to create a fake ajax call would be greatly appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

南街女流氓 2025-01-03 05:12:05

您可以使用SinonJS模拟框架,该框架在假服务器中构建。您可以轻松地将它与茉莉花一起使用:

beforeEach(function() {
        server = sinon.fakeServer.create();
        server.respondWith([200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"])
});

顺便说一句。如果您的 ajax 函数位于全局命名空间中,为什么不调用 spyOn(window, 'ajax')

You can use SinonJS mocking framework, which has a build in fake server. You can easily use it with jasmine:

beforeEach(function() {
        server = sinon.fakeServer.create();
        server.respondWith([200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"])
});

Btw. if your ajax function is in the global namespace why not call spyOn(window, 'ajax')

孤独岁月 2025-01-03 05:12:05

对于单个函数,您可以使用 'createSpy':

/*var */ajax = createSpy('foo');

var 不存在,因为您想重新定义它,但随后要求您定义此间谍的块绑定到实际的相同作用域ajax 已定义。或者,如果您对此感到困惑,请使用 spyOn(window, foo),因为您无论如何都在浏览器中测试它。

有关详细信息,请参阅此答案

关于 ajax 调用,请参阅异步支持部分 新文档,或者更好地使用时钟

window.ajax = function() {};

var response;

var ajaxSpy = spyOn(window, 'ajax').andCallFake(function(url, callback) {
   setTimeout(function() { callback({ 'foo': 'bar' }); }, 1000);
});

jasmine.Clock.useMock();

function callback(resp) { response = resp;  }

ajax('fake.url', callback);

jasmine.Clock.tick(1500);

expect(ajaxSpy).toHaveBeenCalled();
expect(response).toBeDefined();
expect(response.foo).toBeDefined();

Regarding a single function, you may use 'createSpy':

/*var */ajax = createSpy('foo');

var is absent because you want to redefine it, but it is then required that the block where you define this spy is bound to the same scope where real ajax was defined. Or, if you confused with that, use spyOn(window, foo), because you are anyway testing it in the browser.

See this answer for details.

Regarding the ajax call, see Asynchronous Support section in new docs, or better use Clock:

window.ajax = function() {};

var response;

var ajaxSpy = spyOn(window, 'ajax').andCallFake(function(url, callback) {
   setTimeout(function() { callback({ 'foo': 'bar' }); }, 1000);
});

jasmine.Clock.useMock();

function callback(resp) { response = resp;  }

ajax('fake.url', callback);

jasmine.Clock.tick(1500);

expect(ajaxSpy).toHaveBeenCalled();
expect(response).toBeDefined();
expect(response.foo).toBeDefined();
陌路黄昏 2025-01-03 05:12:05

如果您同意不使用间谍,而是使用插件 jasmine-ajax。要模拟单个规范,请使用 withMock

  it("allows use in a single spec", function() {
    var onSuccess = jasmine.createSpy('success');
    jasmine.Ajax.withMock(function() {
      ajax({
            url: 'JSON.php',
            dataType: 'json',           
            onSuccess: onSuccess
      });
      expect(onSuccess).not.toHaveBeenCalled();

      jasmine.Ajax.requests.mostRecent().respondWith({
        "status": 200,
        "responseText": '{"some": "json"}'
      });

      expect(onSuccess).toHaveBeenCalledWith('{"some": "json"}');
    });
  });

仅当您使用 respondWith 时才会发送响应。上面的链接有一些如何安装的说明

If you're ok with not using spies, but instead the add-on jasmine-ajax. To mock for a single spec use withMock:

  it("allows use in a single spec", function() {
    var onSuccess = jasmine.createSpy('success');
    jasmine.Ajax.withMock(function() {
      ajax({
            url: 'JSON.php',
            dataType: 'json',           
            onSuccess: onSuccess
      });
      expect(onSuccess).not.toHaveBeenCalled();

      jasmine.Ajax.requests.mostRecent().respondWith({
        "status": 200,
        "responseText": '{"some": "json"}'
      });

      expect(onSuccess).toHaveBeenCalledWith('{"some": "json"}');
    });
  });

The response is only sent when you use respondWith. The link above has some directions how to install

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文