实际上,我正在编写一个小型JS,以封装对外部Webservice的一些GET和POST调用。是否有一个好的方法/最佳实践如何测试这样的语言?我应该针对GET函数的API编写测试吗?我应该将示例响应放在测试目录中吗?
P.S.:我不能向API发送POST请求,因为它是“实时”系统。
发布于 2014-02-20 18:12:12
您可能需要使用某种单元测试框架,如@BrianDriscoll所述。外面有很多。
我也遇到了这个问题,我没有为JavaScript找到一个很好的AJAX模拟框架。最后,我创建了嘲弄鸟。
用模拟请求的优点
Disadvantages
一个快速而肮脏的例子:
var request = new MockingBird.XMLHttpRequest()
.returnsStatus(200)
.returnsBody('{"message":"I am a teapot"}')
.returnsHeaders({
"Content-Type": "text/json"
});
callSomeFunctionThatUsesAjax(request);
function callSomeFunctionThatUsesAjax(xhr) {
xhr.onreadystatechange = function() {
...
};
xhr.open("POST", "/foo");
xhr.send(null);
}当无法提供自己的AJAX对象时,还可以为情况设置模拟调用:
MockingBird.XMLHttpRequest.disableNetworkConnections()
.mock("/posts/123", "GET", {
status: 404,
body: "Page not found"
})
.mock("/posts/321/comments", "POST", {
status: 201,
responseHeaders: {
"Content-Type": "text/json"
},
body: {
post: {
id: 321,
comment: {
id: 1234
}
}
}
});现在,直接实例化XMLHttpRequest对象的代码甚至不需要知道MockingBird是否存在:
function createComment(postId, text) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState !== 4) return;
if (this.status === 201) {
var data = JSON.parse(this.responseText);
alert("Created comment: " + data.post.comment.id);
}
else if (this.status === 404) {
alert("Post " + postId + " not found!");
}
};
xhr.open("POST", "/posts/" + postId);
xhr.send("post[id]=" + postId + "&post[comment][text]=" + escape(text));
}
createComment(123, "Test Test"); // alert's "Post 123 not found!"
createComment(321, "Test Test"); // alert's "Created comment: 1234"https://stackoverflow.com/questions/21913285
复制相似问题