Почему макет в моем тесте на реагирование возвращает нольJavascript

Форум по Javascript
Ответить
Anonymous
 Почему макет в моем тесте на реагирование возвращает ноль

Сообщение Anonymous »

У меня есть крючок, который извлекает данные из бэкэнд с огненной базой, если хранилище ясно. Крюк < /p>
import { useEffect, useState } from "react";
import useGetUserId from "./useGetUserId";

import { app, firebaseConfig } from "../environments/environment";
import { doc, getDoc, getFirestore } from "firebase/firestore";
import 'firebase/firestore';
import { initializeApp } from "firebase/app";

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(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 {
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
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;
< /code>
Вот модульный тест < /p>
import { renderHook, waitFor } from "@testing-library/react";
import useGetUserProfile from "../../hooks/useGetUserProfile";
import { getDoc } from "../../mocks/firebase/firestore";

jest.mock('firebase/firestore', () => ({
getDoc: jest.fn(),
doc: jest.fn(),
}));

const mockProfile = {
email: 'test@example.com',
username: 'testuser',
userBio: 'Bio',
dob: new Date(),
gender: 'Male',
sexo: 'M',
education: 'University',
drinkingHabits: 'Social',
smokingHabits: 'No',
};

beforeEach(() => {
jest.clearAllMocks();
})

describe("useGetUserProfile", () => {

it("should fetch data correctly", async () => {
getDoc.mockResolvedValue({
exists: () => true,
data: () => mockProfile,
});

const { result } = renderHook(() => useGetUserProfile());
waitFor
console.log('results', result.current)
expect(result.current
).toEqual(mockProfile);
});
});
< /code>
expect(received).toEqual(expected) // deep equality

- Expected - 9
+ Received + 3

Object {
- "dob": 2025-02-11T23:39:25.761Z,
- "drinkingHabits": "Social",
- "education": "University",
- "email": "test@example.com",
- "gender": "Male",
- "sexo": "M",
- "smokingHabits": "No",
- "userBio": "Bio",
- "username": "testuser",
+ "isLoading": false,
+ "setUserProfile": [Function bound dispatchSetState],
+ "userProfile": null,
}
< /code>
console.log
results {
isLoading: false,
userProfile: null,
setUserProfile: [Function: bound dispatchSetState]
}
< /code>
Любая справка была бы очень оценена."firebase": "^11.0.1",
"react": "^18.3.1",


Подробнее здесь: https://stackoverflow.com/questions/794 ... rning-null
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»