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

171
Views
Mocking one function inside of a module, called from inside a component

I'm trying to mock a function inside a utils module.

In my Home component, I have

import { ImageUtils } from "../utils";

const Home: React.FC = () => {
  const [isLoading, setIsloading] = useState(true);

  useEffect(() => {
    ImageUtils.preloadImages(() => {
      setIsloading(false);
    });
  }, []);

  return (
    <div>
      {isLoading ? (
        <p>1 sec...</p>
      ) : (
        <AgamaApp />
      )}
    </div>
  );
}

In "../utils", I have:

export { default as ScreenUtils } from "./screen_utils";
export { default as DateUtils } from "./date_utils";
export { default as LocalStorageUtils } from "./localstorage_utils";
export { default as ImageUtils } from "./image_utils";

And in "utils/image_utils.ts" I have:

import images from "../shared/images";

const preloadImages = (onComplete: () => void) => {
  Promise.all(
    images.map((image) => {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = image.path;
        img.onload = () => {
          resolve(undefined);
        };
        img.onerror = () => reject(new Error("Couldn't load image"));
      });
    })
  ).then(onComplete);
};

export default {
  preloadImages,
};

In my test file, if I do:

import { ImageUtils } from "../utils";

ImageUtils.preloadImages = jest.fn((onComplete) => {
  console.log("function was called");
  onComplete();
});

beforeEach(() => {
  render(<App />);
});

test("drawer slides open when hamburger menu clicked", async () => { ... });

the function never gets called. But if I do

import { ImageUtils } from "../utils";

ImageUtils.preloadImages = (onComplete) => {
  console.log("function was called");
  onComplete();
};

beforeEach(() => {
  render(<App />);
});

test("drawer slides open when hamburger menu clicked", async () => { ... });

everything works fine.

How best can I resolve this and use Jest the way it's supposed to here?

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!