Javascript 深入茉莉花间谍
我想问一些关于茉莉间谍的事。通常我用这样的间谍Javascript 深入茉莉花间谍,javascript,unit-testing,bdd,jasmine,Javascript,Unit Testing,Bdd,Jasmine,我想问一些关于茉莉间谍的事。通常我用这样的间谍 function getAuthrize(id) { $.ajax({ type: "GET", url: "/Account/LogOn" + id, contentType: "application/json; charset=utf-8", dataType: "json" }); } spyOn($, "ajax"); getAuthrize(123); expect($.ajax).toHaveBeenC
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/LogOn
,类型是“Get”
等等,该怎么办
提前感谢您需要使用假的服务器对象 类似于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
对象以检查是否使用特定参数调用了spy,您可以使用来调用它,如下所示:
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')
这将导致可读性更好的错误,因为您可以看到哪个参数是错误的。我没有使用sinon
在corejasmine
中有什么方法可以做到这一点吗?我没有与jasmine一起处理ajax请求。也许这会有所帮助。。