我有一个
JavaScript函数,它发布到远程API,我正在编写单元测试.我想测试的方法是这样的:
var functionToTest = function(callback,fail) { $.ajax({ url: "/myapi/",type: "POST",data: { one: 'one',two: 'two' },accept: "application/json",contentType: "application/json" }).done(function(x) { log = generateLogMessage('Success'); callback(log); }).fail(function(x,s,e) { log = generateLogMessage('Fail'); fail(log); }); }
我有一个单元测试(在QUnit中利用Sinon.js)测试在请求成功时正确调用回调:
QUnit.test('Test that the thing works',function () { var server = this.sandBox.useFakeServer(); server.respondWith( 'POST','/myapi/',[ 200,{'Content-Type': 'application/json'},'{"Success":true}' ] ); var callback = this.spy(); functionToTest(callback,callback); server.respond(); QUnit.ok(callback.calledWith(generateLogMessage('Success'))); });
此测试有效,但无论请求主体是什么,它都会成功返回.我想做的只是假冒服务器响应,如果请求正文是{one:’one’,2:’two’}
解决方法
我打算建议你使用
filtered requests.但是目前的sinon实现是不可能的.
摘自文件:
Add a filter that will decide whether or not to fake a request. The
filter will be called when xhr.open is called,with the exact same
arguments (method,url,async,username,password). If the filter
returns truthy,the request will not be faked.
您无法过滤数据.
编辑:如果我正确理解问题,你可能会做这样的事情:
functionToTest(...); var request = server.requests[0]; var data = JSON.parse(request.requestBody); if (data.one == 'one' && data.two == 'two') { request.respond(200,jsonHeaders,JSON.stringify(specialResponse)); } else { request.respond(200,JSON.stringify(otherResponse)); }
我知道代码会得到你想要的正确结果,但现在还没有办法用sinon以编程方式完成.