Pass ref as context in react-testing-library with jest

Viewed 232

I am trying my hand at unit testing and here is where I am stuck. The refs for inputs are saved in a global context and am trying to mock the context so I can test the components properly.

Issue is once of my components calls the focus() property from the ref and I am not sure how to mock the ref properly so even my test can use the focus() property.

This is my testing code:

import { render as rtlRender, screen } from "@testing-library/react";
import "@testing-library/jest-dom";
import { Provider } from "react-redux";
import store from "../redux/store";
import { GlobalContextProvider } from "../common/GlobalContext";
import { SalesContextProvider } from "../Sales/SalesContext";

import PatientAutocomplete from "../Sales/PatientAutocomplete";

const dummySalesContext = {
  patientRef: null,
};


const dummyGlobalContext = {
  currentComponent: "demo",
  setEnableGlobalNavigation: jest.fn(),
};

const render = (component) =>
  rtlRender(<Provider store={store()}>{component}</Provider>);

test("renders learn react link", () => {
  render(
    <GlobalContextProvider value={dummyGlobalContext}>
      <SalesContextProvider value={dummySalesContext}>
        <PatientAutocomplete
          searchTerm="Demo"
          patientSelected={null}
          close={null}
        />
      </SalesContextProvider>
    </GlobalContextProvider>
  );
  const linkElement = screen.getByText(/Add patient/i);
  expect(linkElement).toBeInTheDocument();
});

This is the error that is thrown: TypeError: Cannot read property 'focus' of undefined

 }, [searchTerm, debounceFetchPatients]);
        useEffect(() => {
           if (!showEditPatient) patientRef.current.focus({ preventScroll: true });
                                                     ^
        }, [showEditPatient]);
0 Answers
Related