У меня есть крючок, который извлекает данные из бэкэнд с огненной базой, если хранилище ясно. Крюк < /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
Почему макет в моем тесте на реагирование возвращает ноль ⇐ Javascript
Форум по Javascript
-
Anonymous
1739318743
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",
Подробнее здесь: [url]https://stackoverflow.com/questions/79431573/why-is-the-mock-in-my-react-unit-test-returning-null[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия