Search code examples
reactjsjestjsexportdefault

How to get Jest to Ignore undefined error for named ESM default exports


I have a React application that I am currently writing tests out for with Jest. It's a large project with over a 100 components, some of which are exported as a default with this syntax

export default SomeAwesomeComponent = () => {
    return (
        <div>
            ...
        </div>
    )
}

This has never affected simply running the application, however when I run jest, jest --watchAll, I get an error for that component ReferenceError: SomeAwesomeComponent is not defined. I understand the difference between named and default exports, as well as how to use them. I can get this working by either

A. removing the name, leaving the 'default export' bit

export default () => {
    return (
        <div>
            ...
        </div>
    )
}

B. declaring SomeAwesomeComponent as a const and than using that as the default export at the end of the file.

const SomeAwesomeComponent = () => {
        return (
            <div>
                ...
            </div>
        )
    }

export default SomeAwesomeComponent;

Given that there are so many components though, not all as default exports but quite a few, it would be very tedious to go through and fix each one. I mean, I will if I need to and eventually will, but for the sake of time, is there a way that I can configure Jest to ignore this error when running tests?


Solution

  • A name is supposed to be provided for named exports but not default export, because it's default.

    export default SomeAwesomeComponent = () => ...;
    

    is the same as

    SomeAwesomeComponent = () => ...;
    
    export default SomeAwesomeComponent;
    

    If there is no SomeAwesomeComponent variable declaration, it tries to assign it to a global. Assigning to undeclared global causes an error in strict mode, which is expected to be enabled by default in modern JavaScript environments. In sloppy mode this pollutes global scope with said identifiers and can accidentally overwrite global variables.

    This syntax is erroneous and doesn't work as intended. Jest doesn't enforce strict mode itself, it's likely enabled by a toolchain that is used to transpile the application, e.g. Babel. Once strict mode is enabled in a script, it cannot be disabled. If the error occurs in multiple places, all of them need to be fixed. This can be done with regular expression replacement in IDE or else.

    This is a shorter fix:

    export default () => ...;
    

    It doesn't provide function name that can be usable for debugging.

    This is a longer fix:

    const SomeAwesomeComponent = () => ...;
    
    export default SomeAwesomeComponent;
    

    export shouldn't necessarily be moved to the end of file but it should occur after SomeAwesomeComponent declaration.