I'm trying to mock up Firebase 9.0.0 onValue() function using Jest. The main component reads a feature using the onValue() function and renders the result.
Acerca.js:
import React, { useEffect, useState } from 'react'
import { db, onValue, ref } from './Firebase'
const Acerca = () => {
const [feature, setFeature] = useState('')
useEffect(() => {
let featureRef = ref(db, 'feature')
let unsubscribe = onValue(featureRef, snapshot => {
setFeature(snapshot.val())
})
return () => unsubscribe()
}, [])
return(
<>{feature ? <h3>{feature}</h3> : null}</>
)
}
export default Acerca
Acerca.test.js:
import React from 'react'
import Acerca from './Acerca'
import { render } from 'react-dom'
import { act } from 'react-dom/test-utils'
import { onValue } from './Firebase'
it("Acerca -> displays title", async () => {
const data = {
feature: {
title: "New feature"
}
}
const snapshot = { val: () => data }
const firebase = { onValue }
const spy = jest.spyOn(firebase, 'onValue').mockImplementation(() => jest.fn((event, callback) => callback(snapshot)))
await act(async () => {
render(<Acerca/>, container)
})
expect(container.querySelector('h3').textContent).toBe(data.feature.title)
})
The problem is that the mock up function is not being called (null value instead of the dummy data) and the test fails:
What is the correct way to mock up the onValue() function?
