在单元测试 Loopback 中,有必要将回调与 upsert 方法结合使用。例如......而不是按照这样的方式写一些东西:
before(function () {
Student = server.models.Student
Course = server.models.Course
Course.upsert({id: 1, key: 'A', department: 'Original department'})
Student.upsert({id: 1, points: 5000})
})
有必要确保回调与更新插入一起使用。由于我有很多模型,所以我在下面初始化我使用异步:
before(function (done) {
Student = server.models.Student
Course = server.models.Course
async.waterfall([
function (callback) {
Course.upsert({id: 1, key: 'A', department: 'Original department'}, callback)
},
function (f, callback) {
Student.upsert({id: 1, points: 5000}, callback)
},
],
function (err, results) {
done(err)
})
})
如何将上面的代码更改为使用 Promises,而不是异步?
我的想法是,有了 Promise,我就能够编写一些如下所示的代码:
before(function (done) {
Student = server.models.Student
Course = server.models.Course
Course.upsert({id: 1, key: 'A', department: 'Original department'})
.then(Student.upsert({id: 1, points: 5000})
.then(function(err) { done(err) }
})
但我一直未能成功兑现 promise 。
编辑以下答案...
before(function (done) {
Course = server.models.Course
Course.upsertWithPromise = Promise.promisify(Course.upsert)
Course.upsertWithPromise({id: 1, key: 'A', department: 'Original department'})
.then(done)
}
it.only('Course upsert', function (done) {
Course.findById(1, function (err, course) {
expect(course.id).to.equal(1)
expect(course.department).to.equal('Original department')
done()
})
})
最佳答案
有两种可能的解决方案。首先是手动 promise 。 您的函数将如下所示:
server.models.Student.upsert = function(data) { // Note NO CALLBACK
return new Promise(function(resolve, reject) {
// Here can do all async staff and when done sucessfully call:
resolve(result);
// OR on error call:
reject(err);
});
}
第二个解决方案将使用库来达到相同的目的。
- var q = require('q');//使用 q 库
- 请勿修改您的模型。他们必须将回调作为最后一个参数(遵循 Node 约定)
- var server.models.Student.upsertWithPromice = q.denodeify(server.models.Student.upsert);
- 利润。
那么您的示例中的代码应该可以正常工作。
关于node.js - Promisfy 环回模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35930540/