为什么是我的React单元测试中的模拟返回null

问题描述 投票:0回答:1

这里是单位测试

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: '[email protected]', 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); }); });

expect(received).toEqual(expected) // deep equality

- Expected  - 9
+ Received  + 3

  Object {
-   "dob": 2025-02-11T23:39:25.761Z,
-   "drinkingHabits": "Social",
-   "education": "University",
-   "email": "[email protected]",
-   "gender": "Male",
-   "sexo": "M",
-   "smokingHabits": "No",
-   "userBio": "Bio",
-   "username": "testuser",
+   "isLoading": false,
+   "setUserProfile": [Function bound dispatchSetState],
+   "userProfile": null,
  }

console.log results { isLoading: false, userProfile: null, setUserProfile: [Function: bound dispatchSetState] }

任何帮助将不胜感激。
"firebase": "^11.0.1", "react": "^18.3.1",
    
我遵循了另一个简化并起作用的教程。

import { renderHook, waitFor } from "@testing-library/react";
import useGetUserProfile from "../../hooks/useGetUserProfile";

jest.mock("../../hooks/useGetUserProfile");
const mockedHook = jest.mocked(useGetUserProfile);
const mockProfile = {
  email: "[email protected]",
  username: "testuser",
  userBio: "Bio",
  dob: "mm/dd/yyyy",
  gender: "Male",
  sexo: "M",
  education: "University",
  drinkingHabits: "Social",
  smokingHabits: "No",
};

describe("Can retrieve user profile when the storage is null", () => {
  it("should return the initial values for data, error and loading", async () => {
    //Arrange
    localStorage.clear();
    mockedHook.mockReturnValue({
      isLoading: false,
      userProfile: {
        email: "[email protected]",
        username: "testuser",
        userBio: "Bio",
        dob: "mm/dd/yyyy",
        gender: "Male",
        sexo: "M",
        education: "University",
        drinkingHabits: "Social",
        smokingHabits: "No",
      },
      setUserProfile: jest.fn(),
    });

    //Act
    const { result } = renderHook(() => useGetUserProfile());

    //Assert
    await waitFor(() => {
      expect(result.current.isLoading).toBe(false);
      expect(result.current.userProfile).toEqual(mockProfile);
    });
  });
});
javascript firebase google-cloud-firestore jestjs react-testing-library
1个回答
0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.