当db是一个自定义类属性时,如何监视/stub/mock firestore db.collection().add()



我有一个类Firestore,它在构造函数this.db中初始化了一个firebase数据库,并有一个addEntry((方法向数据库中添加一个新条目。如何存根/模拟对数据库的写入,以便在测试期间不进行写入?这个测试的断言是db.collection((.add((被调用一次。

firestore.js

class Firestore {

constructor() {
this.db = firestoreAdmin.firestore()
}

async addEntry(newEntry) {
newEntry.claimed = "false"
var collectionReference = await this.db.collection('collection_name').add(newEntry)

return collectionReference._path.segments[1]
}
}

test_firestore.js

const sinon = require('sinon')
const chai = require('chai')
const Firestore = require('../firestore.js')

describe('file firestore.js | class Firestore', function() {
const firestore = new Firestore()
describe('method addEntry(newEntry)', function() {
it('should call this.db.collection().add() once', function() {
var newEntry = {
"client": "clientName"
}
var add = sinon.spy(firestore.db.collection, 'add')
firestore.addEntry(newEntry)
sinon.assert.calledOnce(add)
add.restore()
})
})
})

现在我得到这个错误:

1 failing
1) file firestore.js | class Firestore
method addEntry(newEntry)
should add key:value pair (claimed: false) prior to writing to db:
TypeError: Attempted to wrap undefined property add as function

考虑使用stubsinon文档而不是spysinon文档。spy将封装原始函数,并完全按照原始函数的操作(在您的情况下(写入数据库。

同时,当您想阻止直接调用特定方法时,应该使用stub

var add = sinon.stub(firestore.db.collection, 'add')

根据下面的注释,看起来你正在尝试存根一个复杂的对象,在这种情况下,你实际上可以在没有任何sinon方法的情况下为属性分配一个新值,比如

const fakeAdd = sinon.fake()
firestore.db.collection = [
{add: fakeAdd}
]

firestore.addEntry();
sinon.assert.calledOnce(fakeAdd)

对于异步方法单元测试,您也可以简单地将测试方法标记为async

it('should do something', async () => {
await firestore.addEntry()
})

工作代码笔示例:https://codepen.io/atwayne/pen/VweOXpQ

最新更新