Preciso de ajuda para resolver um erro ao executar testes de unidade em um gancho usado para recuperar dados do usuário.
TypeError: _app.default.auth is not a function 10 | setUserId(storedUserId); 11 | } else { > 12 | const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
Estou recebendo o erro acima somente ao executar testes unitários para um hook que criei para recuperar informações do usuário do storage ou do Firebase. Este hook procura no storage e depois no Firebase se storage === null.
import { useEffect, useState } from "react";
import useGetUserId from "./useGetUserId";
import { app } from "../environments/environment";
import { doc, getDoc, getFirestore } from "firebase/firestore";
const useGetUserProfile = () => {
type profile = {
email: string;
username: string;
userBio: string;
dob: Date;
gender: string;
sexo: string;
education: string;
drinkingHabits: string;
smokingHabits: string;
};
const db = getFirestore(app);
const userId: string | null = useGetUserId();
const [isLoading, setIsLoading] = useState(true);
const [userProfile, setUserProfile] = useState<any | null>(null);
useEffect(() => {
const userProfile = async () => {
setIsLoading(true);
try {
const userRef = localStorage.getItem("PROFILE_INFO");
if (userRef) {
const profile: profile = JSON.parse(userRef);
setUserProfile(profile);
} else {
if (userId) {
const id = JSON.parse(userId);
const userRef = await getDoc(doc(db, "users", id.user.uid));
if (userRef.exists()) {
const profile = userRef.data();
setUserProfile(profile);
}
}
}
} catch (error) {
console.log("error", error);
} finally {
setIsLoading(false);
}
};
userProfile();
}, [setUserProfile]);
return {
isLoading,
userProfile, setUserProfile
};
};
export default useGetUserProfile;
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const firebaseConfig = {
//config properties
};
// Initialize Firebase
export const app = initializeApp(firebaseConfig);
// Initialize Firebase Authentication and get a reference to the service
export const auth = getAuth(app);
E teste de unidade:
// Mocking Firebase Firestore methods
jest.mock('firebase/firestore', () => ({
getFirestore: jest.fn(),
doc: jest.fn(),
getDoc: jest.fn(),
}));
// Mocking localStorage
beforeEach(() => {
jest.spyOn(Storage.prototype, 'getItem').mockImplementation(() => null); // Reset localStorage
});
describe('useGetUserProfile', () => {
it.only('should get user profile from localStorage if available', async () => {
// Mock localStorage with a mock profile
const mockProfile = {
email: '[email protected]',
username: 'testuser',
userBio: 'Bio info',
dob: new Date('1990-01-01'),
gender: 'Male',
sexo: 'M',
education: 'Bachelor',
drinkingHabits: 'Occasionally',
smokingHabits: 'Non-smoker',
};
jest.spyOn(Storage.prototype, 'getItem').mockImplementationOnce(() => JSON.stringify(mockProfile));
const { result } = renderHook(() => useGetUserProfile());
expect(result.current.userProfile).toEqual(mockProfile);
});
Só estou recebendo o erro ao executar o teste de unidade. Acho que deve haver um erro na configuração do Firebase, mas não tenho certeza.
O erro real é que ele está sendo exibido em um hook separado que obtém o UserId, no entanto, os testes de unidade para esse hook não estão falhando.
Aqui está a linha de código real que está causando erros em um teste de unidade do Hook separado.
useEffect(() => {
const storedUserId = localStorage.getItem("USER_CREDENTIALS");
if (storedUserId) {
setUserId(storedUserId);
} else {
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
const uid = user.uid;
localStorage.setItem("USER_CREDENTIALS", uid);
setUserId(uid);
}
});
return () => unsubscribe();
}
}, [userId]);
return userId;
};
Com base no código que você forneceu, desde que o armazenamento local contenha uma entrada para
"USER_CREDENTIALS"
, a lógica que está gerando o erro será ignorada completamente.Quando você simula
localStorage.getItem()
sempre retornarnull
, você faz com que a lógica defeituosa seja executada.Para atualizar essa lógica legada para a nova sintaxe, você usaria o seguinte: