我正在尝试使用 mocha 测试我的 Nodejs API 的一些服务:
exports.getModelts = function () {
return new Promise((resolve, reject) => {
Modelt.find(function (err, modelts) {
if (err) {
return reject(err);
}
return resolve(modelts);
});
});
}
和测试:
it('returns expected payload', function (done) {
service
.getModelts()
.end(function (err, res) {
expect(res.body.length).to.eql(6);
expect(res.body[0].text).to.eql('Todo 1');
done();
});
});
我得到错误:
TypeError: service.getModelts(...).end is not a function
如有任何帮助,我们将不胜感激。
提前致谢。
最佳答案
.end()
是 supertest
的一部分,但您没有在测试中(或您正在测试的方法中)使用它。
相反,您应该在 .then
中进行测试,因为您的方法返回一个 Promise:
it('returns expected payload', function() {
return service
.getModelts()
.then(function(res) {
// I expect that the following tests will fail,
// because they assume that `res` is a `supertest`
// response, and your method returns a Mongoose
// query result
expect(res.body.length).to.eql(6);
expect(res.body[0].text).to.eql('Todo 1');
});
});
(还要注意测试函数如何返回 Promise 链,并且不使用done
;这是因为 Mocha 支持开箱即用的 promises,以及混合 promises使用回调可能会导致问题)。
关于node.js - end() 不是 Node Mocha 测试中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53186948/