【发布时间】:2022-02-15 11:15:46
【问题描述】:
正如标题中所说,我不知道为什么没有将函数 Database.collection(...).onSnapshot 方法作为函数拾取。
我收到的消息错误是:TypeError: Database.collection(...).onSnapshot is not a function
我试图让它像这样工作:
test.only('should react when a new record is created', async () => {
jest.mock('@google-cloud/firestore', () => jest.fn(() => ({
collection: jest.fn()
.mockImplementationOnce(function () { return this })
.mockImplementationOnce(function () { return this })
.mockImplementationOnce(function () { return this })
.mockImplementationOnce(function () { return this })
.mockImplementationOnce(function () { return this })
.mockImplementationOnce(function () { return this })
.mockResolvedValueOnce(() => {
return {
onSnapshot: () => {} // HOW TO MAKE IT WORK AS A FUNCTION?
}
}),
get: jest.fn().mockResolvedValue({ docs: [] }),
doc: jest.fn().mockReturnThis(),
set: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
select: jest.fn().mockReturnThis()
})))
const StatisticsService = require('./index')
await StatisticsService()
})
代码逻辑:
const Firestore = require('@google-cloud/firestore')
const Database = new Firestore()
const collections = ['products', 'users', 'orders']
collections.forEach(collection => {
Database.collection(collection).onSnapshot(snapshot => {
console.log('????????????', snapshot)
snapshot.docChanges().forEach(change => {
if (change.type === 'added') this.onDatabaseRecordCreated(collection, change.doc.data())
if (change.type === 'modified') this.onDatabaseRecordUpdated(collection, change.doc.data())
if (change.type === 'removed') this.onDatabaseRecordRemoved(collection, change.doc.data())
})
}, error => {
console.error(error)
})
})
【问题讨论】:
标签: node.js unit-testing google-cloud-firestore jestjs