【发布时间】:2021-02-13 21:34:50
【问题描述】:
我正在尝试对使用 Promise 重写的代码进行单元测试。 FileFactory 类具有以下异步功能:
async getFileHandler(filePath) {
var self = this;
for(const item of self.privateFileHandlers) {
await item.canHandle(filePath)
.then(function(response) {
console.log("Response:",JSON.stringify(response)); //line A
return response;
}, function(error) {
return error;
//ignore since most handlers won't be able to handle.
//also, the callback after the loop will inform that no filehandler was found.
})
.catch(function(err){
//console.log('Catching: ',JSON.stringify(err));
return err;
//ignore since most handlers won't be able to handle.
//also, the callback after the loop will inform that no filehandler was found.
});
}
}
我在 A 行登录的响应包含我所期望的内容。
但是,在我的单元测试中,我没有得到响应对象。
it('should return correct FileHandler child instance', function(){
var ff = new FileFactory();
ff.getFileHandler("./tests/H1_20180528.csv").then(function(value) {console.log("Success",JSON.stringify(value));}).catch(function(err) {console.log("Fail",JSON.stringify(err));});
//ff.getFileHandler("./tests/H1_20180528.csv").then(value => console.log("Success",JSON.stringify(value)));
//console.log(JSON.stringify(fh));
});
我在这里缺少什么? 谢谢。
这行得通:
async getFileHandler(filePath) {
var self = this;
for(const item of self.privateFileHandlers) {
try {
let response = await item.canHandle(filePath);
if(response.status === "success")
return response;
} catch(e) {
//ignore so it does not return on failed canHandle calls.
}
}
throw 'No supporting file handler available.';
}
//更新的单元测试
describe('Select handler', function () {
it('should fail and return no file handler.', function () {
var ff = new FileFactory();
ff.getFileHandler("./tests/H1_20180528_fail2.csv")
.then(function (value) {
chai.assert(value.status === null);
})
.catch(function (err) {
chai.assert(err !== null);
});
});
it('should return correct FileHandler child instance', function () {
var ff = new FileFactory();
ff.getFileHandler("./tests/H1_20180528.csv")
.then(function (value) {
chai.assert(value.status === 'success');
})
.catch(function (err) {
chai.assert(err === null);
});
});
});
【问题讨论】:
-
async和await的全部意义在于它们允许您避免明确的 Promise 争吵。await fn()之后的代码被隐式视为在.then()回调中。 -
value在你的测试中你期待什么?你的getFileHandler没有return任何东西。 -
为什么要复制错误处理代码?
-
我来自 OOP,这是我第一次处理 JS 中的 Promise。承诺的结构提供了拒绝和捕获,所以我都填写了。事实证明这里不需要。
标签: javascript asynchronous async-await promise es6-promise