【问题标题】:Going deep into jasmine spy深入茉莉花间谍
【发布时间】:2013-06-04 05:52:23
【问题描述】:

我想问一些关于 jasmine spy 的事情。通常我像这样使用间谍

function getAuthrize(id) {
$.ajax({
    type: "GET",
    url: "/Account/LogOn" + id,
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});
}
spyOn($, "ajax");
getAuthrize(123);
expect($.ajax).toHaveBeenCalled();

但我想知道,如果我想验证更多的东西,比如(在 ajax 调用中调用的 url/Account/LogOntype is 'Get' 等等。

提前致谢

【问题讨论】:

    标签: javascript unit-testing bdd jasmine


    【解决方案1】:

    要检查是否使用特定参数调用了间谍,您可以使用 toHaveBeenCalledWith,如下所示:

    expect($.ajax).toHaveBeenCalled({
        type: "GET",
        url: "/Account/LogOn" + id,
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
    

    但是当 JSON 中只有一个字段错误时,这将成为一个非常难以阅读的错误。

    另一种方法是使用mostRecentCall.args:

    var args = $.ajax.mostRecentCall.args[0];
    expect(args.type).toEqual('GET')
    expect(args.url).toEqual('/Account/LogOn123')
    

    这将导致更好的可读性错误,因为您可以看到哪个参数错误。

    【讨论】:

      【解决方案2】:

      为此,您需要使用伪造的服务器对象

      类似sinon.fakeServer

      describe('view interactions', function(){
          beforeEach(function() {
              this.saveResponse = this.serverResponse.someObj.POST;
              this.server = sinon.fakeServer.create();
              this.server.respondWith(
                    'POST',
                     this.saveResponse.url,
                     this.validResponse(this.saveResponse)
              );
          });
      
          afterEach(function() {
           this.server.restore();
          });
      });
      

      需要确保您已定义 this.serverResponse 对象

      【讨论】:

      猜你喜欢
      • 2014-01-25
      • 2012-08-15
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多