Mock a function twice with Jest

Solution for Mock a function twice with Jest
is Given Below:

So, I was testing a react component (it’s actually an integration testing) and I have this:

const Component = ({ children }) => {
  const [file, setFile] = React.useState({ name: null });
  const [slugConfig, setSlugConfig] = React.useState({ slug: '', error: null });

  const handleSubmit = jest.fn();

  const childrenWithProps = React.Children.map(children, child => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, {
        handleSubmit,
        slugConfig,
        file,
        setFile,
        setSlugConfig,
      });
    }
    return child;
  });

  return <div>{childrenWithProps}</div>;
};

Which is a mock to serve that Form. The Form component uploads a file, zip file, and has some validations when it’s not .zip|.rar it will show an error.

So, problems is:
I have to test if it is a zip and a rar. However the file transformer returns only the name property (which is what I have to test)

module.exports = { name: 'file.ext' };

I mocked it:

jest.mock('../../../../helpers/file-transformer', () => {
  return { name: 'file.zip' };
});

But I have to mock it to test it with another extension. How would I be able to do that?

  • I can’t spy, ’cause it is not a function;
  • Even if it was a function when testing jest will return this: { process: [Function: process] }