React unit test cases for axios blob with window.open?

Hi I tried to right the unit test case in react using axios, jest and enzyme.

My Test cases shows good coverages, but it seems like it is not covering few lines or function. It does not cover window.open

I tried to write some unit test using different approaches but seesm like no luck can anyone please help on this?

Below are test cases:
Solution 1

describe("handleOpenIdCards function", () => {
  const mockWindowOpen = jest.fn();
  let wrapper;
  let notIsNarrowMobile = {
    isMedium: true,
    isNarrowMobile: false,
    coverageData: ["EEDental", "EEVision", "Dental"]
  };
  beforeAll(() => {
    global.open = jest.fn();
  });

  beforeEach(() => {
    const subscriberId = "mocked_subscriber_id";
    wrapper = mount(
      <OverviewCard {...notIsNarrowMobile} subscriberId={subscriberId} />
    );
  });

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

  afterAll(() => {
    global.open.mockRestore();
  });

  it("should handle dental card correctly", async () => {
    const mockApiResponse = {
      data: "Mock PDF Data"
    };
    axios.mockResolvedValue(mockApiResponse);

    await act(async () => {
      wrapper
        .find('[data-test-id="card-button-option1"]')
        .at(0)
        .simulate("click", { target: { value: "Dental ID Cards" } });
    });

    expect(axios).toHaveBeenCalledTimes(1);

    // Verify the API call parameters
    expect(axios).toHaveBeenCalledWith({
      url: expect.stringContaining("dental-vision-id-cards"),
      method: "GET",
      responseType: "blob",
      apikey: process.env.REACT_APP_NEWEXP_API_KEY
    });

    expect(global.open).toHaveBeenCalledTimes(1);
    expect(mockWindowOpen).toHaveBeenCalledWith(
      expect.stringContaining("dental-vision-id-cards"),
      "_blank"
    );
  });
});


**Solution 2**

it("should handle the 'Dental ID Cards' click PDF", async () => {
    const windowOpen = window.open;
    window.open = jest.fn();
    let environmentEnding = "";
    const subscriberId = "mocked_subscriber_id";
axios.mockResolvedValue({
  data: "dummy pdf data"
});

const wrapper = mount(
  <OverviewCard {...notIsNarrowMobile} subscriberId={subscriberId} />
);

wrapper
  .find('[data-test-id="card-button-option1"]')
  .at(0)
  .simulate("click", { target: { value: "Dental ID Cards" } });

const ssoEnvironment = "_ITEST";
getCookie(`unumEnterpriseSSO${ssoEnvironment}`);

const environment = evaluateEnvironment();
if (["itest1", "dev1"].includes(environment)) {
  environmentEnding += `/${environment}`;
}

expect(axios).toHaveBeenCalledWith({
  url: `${newExperienceMumApiUrl}/dental-vision-id-cards${environmentEnding}?productType=dental&subscriberId=${subscriberId}`,
  method: "GET",
  responseType: "blob",
  apikey: process.env.REACT_APP_NEWEXP_API_KEY
});

window.open = windowOpen;  });

And below is the function I am trying to write test cases

 const handleOpenIdCards = value => {
    const unumEnterpriseSSOValue = getCookie(
      `unumEnterpriseSSO${ssoEnvironment}`
    );
    const environment = evaluateEnvironment();

    if (["itest1", "dev1"].includes(environment)) {
      environmentEnding += `/${environment}`;
    }

    let idCardPath = "";
    if (value === _dentalCard) {
      idCardPath = `${newExperienceMumApiUrl}/dental-vision-id-cards${environmentEnding}?productType=dental&subscriberId=${subscriberId}`;
    } else {
      idCardPath = `${newExperienceMumApiUrl}/dental-vision-id-cards${environmentEnding}?productType=vision&subscriberId=${subscriberId}`;
    }

    axios({
      url: idCardPath,
      method: "GET",
      responseType: "blob",
      apikey: process.env.REACT_APP_NEWEXP_API_KEY
    })
      .then(response => {
        const pdfBlob = new Blob([response.data], { type: "application/pdf" });
        const pdfUrl = URL.createObjectURL(pdfBlob);

        const pdfWindow = window.open(pdfUrl, "_blank");

        pdfWindow.addEventListener("beforeunload", () => {
          URL.revokeObjectURL(pdfUrl);
        });
      })
      .catch(error => {
        console.error("Error fetching PDF:", error);
      });
  };

These are the lines not covered but important to cover.

image

Any Help, guidance or suggestion would really help me. Thanks all experts.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.