【发布时间】:2019-08-23 12:42:42
【问题描述】:
我正在尝试使用 Mocha 在我的 Express/Node 后端测试一个函数。我创建了一个由函数修改的实际参数的存根:它有一个在 getValue 中调用的send 方法(我要测试的函数)和一个ready 参数,当我初始化一个新的承诺时当在存根上调用 send 时,存根被创建并解析。
我正在尝试await 这个承诺,但它只是挂起(然后摩卡超时测试)。下面的 setTimeout 打印出Promise { 'abc' },我认为这意味着承诺已按预期解决,但等待永远不会完成。
这是测试文件中的相关代码:
function ResStubTemplate() {
return {
_json: undefined,
_message: undefined,
json: function(x) {
this._json = x;
return this;
},
send: function(message) {
this._message = message;
this.ready = Promise.resolve("abc");
return this;
},
ready: new Promise(_ => {})
}
}
// This is the test
it("should get the value.", async function(done) {
let req = { query: { groupId: 12345 } };
res = ResStubTemplate();
controller.getValue(req, res);
setTimeout(() => console.log(res.ready), 1000); // prints Promise { 'abc' }
let x = await res.ready; // hangs??
console.log(x); // never prints
done();
}
这是测试文件中的相关代码:
exports.getValue = function(req, res) {
ValueModel.findOne({groupId: req.query.groupId})
.then(value => res.json({value: value}).send();
};
我得到的错误是:
Error: Timeout of 5000ms exceeded.
For async tests and hooks, ensure "done()" is called; if returning a Promise,
ensure it resolves. (/.../test/api/controller_test.js)
【问题讨论】:
-
new Promise(_ => {})这将永远无法解决。
标签: javascript node.js express async-await mocha.js