1

Following are my code which includes the fetch API(getData) call with the useEffect and once get the response it will set the result into the setData using useState

I am trying to write the test case for the useEffect and useState but its failing and when I am seeing into the coverage ,I am getting the red background color with statements not covered for the useEffect block.

import { getData } from '../../api/data';

const [data, setData] = useState({});

  useEffect(() => {
    getData({ tableName }).then((response) => {
      try {
        if (response && response.result) {
          const result = Array.isArray(response.result)
            ? response.result[0]
            : response.result;
          const createDate = result.createdDate;
          result.name = result.firstName;
          result.submittedDate = `${createDate}`;
          result.attribute = Array.isArray(result.attribute)
            ? result.attribute
            : JSON.parse(result.attribute);
          setData(result);
        }
      } catch (error) {
        const errorObj = { error: error.message || 'error' };
        setData({ errorObj });
      }
    });
  }, []);

And I tried to write the test cases as following for the above code.

import React from "react";
import {
  shallowWithIntl,
  loadTranslation,
} from "../../../node_modules/enzyme-react-intl/lib/enzyme-react-intl";

import ParentPage from "ParentPage";
import ChildPage from "ChildPage";
import mockResponse from "mockData";
import { shallow, mount } from "enzyme";
import { act } from "react-dom/test-utils";


global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve(mockResponse),
  })
);

describe("ParentPage", () => {
  let useEffect;
  let wrapper;
  const mockUseEffect = () => {
    useEffect.mockImplementationOnce((f) => f());
  };

  beforeEach(() => {
    const defaultProps = {
      tableName: "tableName",
    };

    wrapper = shallowWithIntl(<ParentPage {...defaultProps} />);
    useEffect = jest.spyOn(React, "useEffect");
    mockUseEffect();
  });

  it("Should render", () => {
    expect(wrapper).toMatchSnapshot();
  });
  it("Compenent render", async () => {
    let wrapper;
    await act(async () => {
      const setWidgets = jest.fn();
      const useStateSpy = jest.spyOn(React, "useState");
      useStateSpy.mockImplementation([mockResponse, setWidgets]);
      wrapper = await mount(<ChildPage data={mockResponse} />);
     
      await act(async () => {
        wrapper.update();
      });
      console.log(wrapper);
    });
  });
});

But when I tried using npm run test,And check the coverage I am still getting the statements not covered for the useEffect and useState.

What should I do to achieve the coverage as maximum as possible?

Nimantha
  • 6,405
  • 6
  • 28
  • 69

0 Answers0