提问人:hokkyo 提问时间:11/14/2023 更新时间:11/14/2023 访问量:16
TypeError:callback 不是函数。如何将这个摩卡测试转换为异步测试?
TypeError: callback is not a function. How to transform this mocha test to async testing?
问:
这是一个管理资源的简单 Web 应用程序。我正在将 MongoDB 和 Mongoose 用于数据库,我正在尝试测试 findOne() mongoose 函数。它将属性作为参数,并查找符合要求的实体。现在,我教摩卡进行测试的老师使用了一个 5-6 年前的视频。从那时起,猫鼬发生了变化,摩卡也发生了变化。我的测试代码就在这里,下面是我测试的中间件。
测试
const expect = require('chai').expect;
const getResourceMW = require('../../../../middleware/Resource/getResourceMW');
describe('getResourceMW middleware ', function () {
it('should return resource', function (done) {
const mw = getResourceMW({
ResourceModel: {
findOne:(p1,cb)=>{ //<------- THIS PART
cb(null,'mock resource')
}
}
});
mw({
params:{
resourceid : '42'
}
},{
locals:{
}
},()=>{
done();
})
});
});
中间件
const requireOption = require('../requireOption');
module.exports = function(objectRepository) {
const ResourceModel = requireOption(objectRepository,'ResourceModel');
return function (req,res,next){
ResourceModel.findOne({_id: req.params.resourceid})
.then(function(resource){
res.locals.resource = resource;
return next();
})
.catch(function (err){
console.log(err);
return next(err);
});
}
};
错误是这样的:
摩卡 .\getResourceMW.js
getResourceMW 中间件 1)应该返回资源
0 次通过 (5ms) 1 失败
- getResourceMW 中间件 应该返回资源:TypeError:cb 不是函数
Mongoose 现在使用的 findOne 不是回调,而是 .then,正如您在我的代码中看到的那样。我应该如何更改我的测试代码(第一个,注释箭头所在的位置),以便我可以测试猫鼬的 findOne 函数?
答: 暂无答案
评论