我正在尝试测试 mysqlite3 数据访问层,但我似乎无法正确地 stub 我的 db.all() 方法,我不确定这是由于我的数据库是如何传入的还是我 stub 错误.
这是我的数据库文件:
const db = new sqlite3.Database(path.join(__dirname, '
../database/example.db'), (err) => {
if (err) return console.log(err.message)
console.log('Connected to the database')
})
module.exports.database = db
这是我要 stub 的函数:
const db = require('./database.js').database
module.exports.selectMultiple = request => {
//unimportant code
return new Promise((resolve, reject) => {
db.all(sql, (err, rows) => {
if (err)
reject(err)
else {
resolve('blah blah blah')
})
})
}
这是我的尝试,但我似乎无法开始工作:
const db = require('../../data_access/database.js').database
describe('select multiple', () => {
beforeEach(() => {
const testProduct2 = JSON.parse(JSON.stringify(testProduct))
testProduct2['key'] = '2'
this.multiple = sinon.stub(db, 'all')
.resolves([testProduct, testProduct2])
})
afterEach(() => {
this.multiple.restore()
})
test('select 2 products', async(done) => {
expect.assertions(2)
const macbooks = await productDb.selectMultiple({amount: 2})
expect(macbooks.length === 2).toBe(true)
expect(macbooks[0].key !== macbooks[1].key).toBe(true)
done()
})
})
如果我运行这个异步测试 block 超时。有谁知道我应该如何 stub ?
谢谢!
最佳答案
问题
db.all
不返回 Promise,它使用回调作为第二个参数。
stub.resolves
导致 stub 返回一个 Promise,因此永远不会调用回调并且由 selectMultiple
返回 Promise永远不会解决导致测试超时 await productDb.selectMultiple({ amount: 2 })
.
解决方案
stub db.all
使用 stub.callsArgWith
这样作为第二个参数传递的回调被调用:
describe('select multiple', () => {
beforeEach(() => {
const testProduct2 = JSON.parse(JSON.stringify(testProduct))
testProduct2['key'] = '2'
this.multiple = sinon.stub(db, 'all')
.callsArgWith(1, null, [testProduct, testProduct2]); // use stub.callsArgWith
})
afterEach(() => {
this.multiple.restore()
})
test('select 2 products', async () => {
expect.assertions(2)
const macbooks = await productDb.selectMultiple({ amount: 2 })
expect(macbooks.length === 2).toBe(true) // SUCCESS
expect(macbooks[0].key !== macbooks[1].key).toBe(true) // SUCCESS
})
})
另请注意,您不需要使用 done
因为您使用的是 async
测试功能并正在使用 await
正在调用 productDb.selectMultiple
.
关于javascript - 使用 sinon 测试 promise 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53439141/