cjmling / findings

Notes on stuff i finds worth keeping for quick reference later on.
2 stars 0 forks source link

How to change mock value in each test #348

Open cjmling opened 6 months ago

cjmling commented 6 months ago

use mockImplementation

https://chat.openai.com/share/0e33ca40-051c-46fc-b29e-c24a3f7d8b0e

import userProfile from "../../scripts/userProfile";

jest.mock("../../scripts/userProfile", () => {
  const originalUserProfile = jest.requireActual("../../scripts/userProfile");

  return jest.fn(() => ({
    ...originalUserProfile,
    user: {
      _id: "aaaaaaaaaaaaaaaaaaaaaaaa",
    },
    setShowUsernameUpdateDialog: mockSetShowUsernameUpdateDialog,
  }));
});

describe("Your test suite", () => {
  beforeEach(() => {
    // Reset the mock implementation before each test
    userProfile.mockClear();
  });

  test("Test case 1", () => {
    // Customize the user value for this test
    userProfile.mockImplementation(() => ({
      user: {
        _id: "bbbbbbbbbbbbbbbbbbbbbbbb",
      },
      setShowUsernameUpdateDialog: mockSetShowUsernameUpdateDialog,
    }));

    // Your test code here
  });

  test("Test case 2", () => {
    // Customize the user value for this test
    userProfile.mockImplementation(() => ({
      user: {
        _id: "cccccccccccccccccccccccc",
      },
      setShowUsernameUpdateDialog: mockSetShowUsernameUpdateDialog,
    }));

    // Your test code here
  });

  // Add more test cases as needed
});