dimanche 7 mars 2021

Mocking an API function gives error while testing the code

Below is my App.js code for your reference

import React from "react";
import "./App.css";
import axios from "axios";

function App() {
  const fetchTheComments = async () => {
    let commentsFetched = await axios.get(
      `https://jsonplaceholder.typicode.com/comments/1`
    );
    return commentsFetched;
  };

  return (
    <div className="App">
      <h1>Testing Jest-Enzyme</h1>
      <button
        id="fetch-comments"
        onClick={() => {
          fetchTheComments();
        }}
      >
        Fetch
      </button>
      <p>
        {JSON.stringify(fetchTheComments())
          ? JSON.stringify(fetchTheComments())
          : ""}
      </p>
    </div>
  );
}

export default App;

Below is my App.test.js code for your reference

import App from "./App";
import { mount } from "enzyme";
import mockAxiosApi from "../src/__mocks__/mockAxiosApi";

describe("Before testing", () => {
  let wrapper;
  beforeAll(() => {
    wrapper = mount(<App />);
  });
  test("render the correct title", () => {
    expect(wrapper.find("h1").text()).toBe("Testing Jest-Enzyme");
  });
  test("button click", () => {
    wrapper.find("#fetch-comments").simulate("click");
    expect(wrapper.find("comments")).not.toBe("");
  });
  test("should fetch comments", async () => {
    wrapper.find("#fetch-comments").simulate("click");
    mockAxiosApi.get.mockImplementationOnce(() =>
      Promise.resolve({
        data: {},
      })
    );
    console.log(wrapper.debug());
    let response = await wrapper.instance().fetchTheComments();
    console.log(response);
  });
});

Getting the below error while doing npm run test

I am not sure why i am getting the error, i have one lambda function inside the component which i am testing but whenever i run a test getting an error stating fetchTheComments function is null. I have pasted my App.js and App.test.js here for your reference. Can someone help me in this issue ?

Aucun commentaire:

Enregistrer un commentaire