I am starting to use Jest for testing my React app, I am writing a basic test and I have an exception. The test code is the following
// __test__/App.test.js
import '@babel/polyfill'
import React from 'react';
import App from '../components/App'
import { render } from '@testing-library/react';
jest.mock('firebase/app')
// The error is the same with or without the following line:
firebase.analytics.mockResolvedValue(null)
it("renders without crashing", () => {
render(<App />);
});
But when I run npx jest
I get this output:
FAIL src/__test__/App.test.js
● Test suite failed to run
TypeError: firebase.analytics is not a function
8 | // Initialize Firebase
9 | firebase.initializeApp(firebaseConfig);
> 10 | firebase.analytics();
| ^
11 |
12 | const db = firebase.firestore();
13 |
The app works as it should outside tests.
How can I do to propperly mock firebase to simply test than App renders without errors?
If someone is interested: I found the way to do this. I am mocking the functions I am using:
// __mocks__/firebase/app.js
module.exports = (function () {
const _tareas = { ...initialData }
return {
initializeApp: () => null,
analytics: () => null,
firestore: () => ({
collection: () => ({
get: () => ({
docs: _tareas.list.map(index => ({
data: () => _tareas.byId[index],
id: index,
}))
}),
add: (tarea) => {
const newIndex = _tareas.list.length
_tareas.list.push(newIndex)
_tareas.byId[newIndex] = tarea
},
})
}),
}
})()
I also had to create blank files __mocks__/firebase/analytics
and __mocks__/firebase/firestore
I am going to implement the functions as I am needing them
Now it works as I expect
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.