繁体   English   中英

深入了解茉莉间谍

[英]Going deep into 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'等)。

提前致谢

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

sinon.fakeServer类的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对象

要检查是否使用特定参数调用了间谍,可以像下面这样使用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')

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM