0

我想问一些关于 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();

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

提前致谢

4

2 回答 2

0

为此,您需要使用假服务器对象

就像是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定义对象

于 2013-06-04T06:01:19.073 回答
0

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

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

于 2013-06-04T06:30:40.877 回答