Bea*_*der 8 javascript unit-testing qunit sinon
我有一个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);
});
}
Run Code Online (Sandbox Code Playgroud)
我有一个单元测试(在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')));
});
Run Code Online (Sandbox Code Playgroud)
此测试有效,但无论请求主体是什么,它都会成功返回.我想要做的只是假冒服务器响应请求正文{ one: 'one', two: 'two' }
sgt*_*dck 12
差不多两年后,但仍然相关:
这可以通过将函数而不是数组作为第三个参数传递来实现server.respondWith.该函数接受一个参数'request',您可以在其上调用request.respond(statusCode, headers, body);
你仍然需要从中提取值request.requestBody,但至少它是可行的.
QUnit.test('Test that the thing works', function () {
var server = this.sandbox.useFakeServer();
server.respondWith(
'POST',
'/myapi/',
function (request) {
console.log(request.requestBody); // <- assert here :-)
request.respond(200, {'Content-Type': 'application/json'}, '{"Success":true}');
}
);
var callback = this.spy();
functionToTest(callback, callback);
server.respond();
QUnit.ok(callback.calledWith(generateLogMessage('Success')));
});
Run Code Online (Sandbox Code Playgroud)
我打算建议您使用过滤请求。然而,这在目前的 sinon 实现中是不可能的。
文档摘录:
添加一个过滤器来决定是否伪造请求。当调用 xhr.open 时,将使用完全相同的参数(方法、url、异步、用户名、密码)调用过滤器。如果过滤器返回 true,则请求不会被伪造。
您没有能力过滤数据。
编辑:如果我正确理解问题,你也许可以做这样的事情:
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, jsonHeaders, JSON.stringify(otherResponse));
}
Run Code Online (Sandbox Code Playgroud)
我知道代码会得到您想要的正确结果,但现在没有办法用 sinon 以编程方式实现这一点。
| 归档时间: |
|
| 查看次数: |
3312 次 |
| 最近记录: |