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?