[英]Unit testing javascript promises
My code fetches data from a server via ajax and uses promises. 我的代码通过ajax从服务器获取数据并使用promises。
How do I write a unit text for this code? 如何为此代码编写单元文本?
function getPromise(){
var p = new Promise(function(resolve, reject) {
http.get({
host: 'localhost',
port: 3000,
path: '/blist'
}, function(res) {
if(res.statusCode < 200 || res.statusCode>300) {
reject('statusCode=' + res.statusCode);
return;
}
var data="";
res.on('data', function (chunk) {
data += chunk;
resolve(data);
return;
});
res.on('error', function(error) {
console.log("Got error: " + e.message);
reject(error);
});
})
});
return p;
}
I guess you'd want to test the promise function, whether it's gonna do what's expected if you fake an http call. 我猜你想要测试一下promise功能,不管它是否会做假的http呼叫。
For that you might wanna consider passing in http object and the callback it takes as parameters so you can mock them and simulate the success and error responses in your tests. 为此,您可能需要考虑传入http对象及其作为参数的回调,以便您可以模拟它们并模拟测试中的成功和错误响应。
Something like 就像是
getPromise(http, req, callback) {
var promise = new Promise((resolve, reject) -> {
http.get(req, callback);
callback.on('data', data -> { // Resolve or reject looking at the status code })
})
return promise;
}
Then you can mock your callback as well as http#get function to test your scenarios 然后你可以模拟你的回调以及http#get函数来测试你的场景
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.