【发布时间】:2018-11-23 19:51:06
【问题描述】:
使用 sinon 如何在 db.run 函数中存根/伪造 this.lastID 的返回值。
module.exports.insert = async(request) => {
//unimportant code
return new Promise((resolve, reject) => {
db.run(sql, params, function(err) {
if (err)
reject(err)
else
resolve(this.lastID)
})
})
}
我可以使用以下代码伪造回调:
describe('insert', () => {
beforeEach(() => {
this.insert = sinon.stub(db, 'run')
.callsArgWith(2, null)
})
afterEach(() => {
this.insert.restore()
})
test('add product to the database', async(done) => {
expect.assertions(1)
const id = await productDb.insert(testProductAlt)
expect(isNaN(id)).toBe(false)
expect(id).toBe('1')
done()
})
})
但由于 this.lastID 未定义,它会失败。我该如何克服这个问题?
谢谢!
【问题讨论】:
标签: javascript node.js jestjs sinon