我试图弄清楚如何测试进行异步调用的同步方法。
我在下面有此方法,我想简单地测试并断言res.status(HttpStatus.OK).send()
返回200响应
'use strict'
const HttpStatus = require('http-status-codes')
let db = null
/**
* Gets a resource by id
* @param {Object} req The request object
* @param {Object} res The response object
* @return {Object} An http response
*/
function getById (req, res) {
const dockey = req.params.resourceType + '$' + req.params.id
// The get by id query
const query = ResourceTypesDao.getByIdQuery()
db.transaction({
write: ['auditevents', 'auditedges'],
read: ['clindocs']
},
query,
{
key: dockey,
id: req.params.id
})
.then(result => {
return res.status(HttpStatus.OK).send()
.catch(err => {
console.log('err = ', err)
})
}
module.exports = (database) => {
db = database
return getById
}
对应的规范文件
'use strict'
const expect = require('chai').expect
let db = {
transaction: function(collections, query, params) {
return new Promise((resolve, reject) => {
return resolve({doc: {}})
})
}
}
const getById = require('../../../src/controllers/resource-types/getById')(db)
let req = {
params: {
id: 'foo'
}
}
let res = {
status: function() {
let self = {}
function send() {
}
self.send = send
return self
},
send: function() {
}
}
describe.only('#getById', () => {
it('should pass', (done) => {
const result = getById(req, res)
setTimeout(() => {
console.log('result = ', result) <-- returning undefined so this aint right
expect(result).to.be.instanceOf(Object)
done()
}, 1000)
})
})
答案 0 :(得分:0)
您需要从getById
函数返回承诺:
function getById (req, res) {
...
return db.transaction({...}).then(...).catch(...);
}
然后在您的测试中,等待其解决后再声明:
it('should pass', (done) => {
getById(req, res)
.then(result => {
// make assertion here
done()
});
});