如果引用是局部作用域常量 (topicsRef),我就能够通过测试。如果它是一个全局范围常量(topicRef - 在topics.ts 开头导入)那么测试失败,因为常量未定义。有没有什么方法可以在不声明局部作用域常量而只使用全局作用域常量的情况下通过测试?
firebase/索引:
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/firestore'
import 'firebase/storage'
import 'firebase/functions'
import { firebaseConfig } from './config'
if (firebase.apps.length === 0) {
firebase.initializeApp(firebaseConfig)
}
export const db = firebase.firestore()
export const topicRef = db.collection('topics')
topics.ts:
import { topicRef } from 'firebase/index'
import { TopicsType } from 'types/topics'
export const fetchTopics = (): Promise<TopicsType | undefined> => {
const topicsRef = firebase.firestore().collection('topics')
return new Promise((resolve, reject) => {
return topicsRef
.orderBy('created_at', 'desc')
.get()
.then((snapshots) => {
const data = []
snapshots.forEach((topic) => {
data.push(topic.data())
if (!data) {
console.error('Error')
reject(undefined)
} else {
resolve(data)
}
})
})
.catch((error) => {
console.error(error.message)
reject(undefined)
})
})
}
FetchTopic.test.tsx:
import { mockFirebase } from 'firestore-jest-mock'
import { getPage } from 'next-page-tester'
import { screen } from '../test-utils'
import { fetchTopics } from 'lib/topics'
import { mockCollection, mockOrderBy } from 'firestore-jest-mock/mocks/firestore'
jest.mock('firebase/index', () => {
mockFirebase({
database: {
topics: [
{
id: 'testtesttest',
all_day: false,
closed: false,
created_at: { seconds: 1626400885, nanoseconds: 372000000 },
description: 'testtesttest',
event_date: {
end_date: { seconds: 1626400859, nanoseconds: 372000000 },
start_date: { seconds: 1626400859, nanoseconds: 372000000 },
},
genre: 'information',
title: 'testtesttest',
topic_id: 'testtesttest',
updated_at: { seconds: 1626400885, nanoseconds: 373000000 },
},
{
id: 'testtesttest',
all_day: false,
closed: false,
created_at: { seconds: 1626400885, nanoseconds: 372000000 },
description: 'testtesttest',
event_date: {
end_date: { seconds: 1626400859, nanoseconds: 372000000 },
start_date: { seconds: 1626400859, nanoseconds: 372000000 },
},
genre: 'information',
title: 'testtesttest',
topic_id: 'testtesttest',
updated_at: { seconds: 1626400885, nanoseconds: 373000000 },
},
],
},
})
})
describe('fetch topics functions', () => {
it('should return data', async () => {
await fetchTopics()
expect(mockCollection).toHaveBeenCalledWith('topics')
expect(mockOrderBy).toHaveBeenCalledWith('created_at', 'desc')
})
})
})