Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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]);
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!