sweetalert2 / sweetalert2-react-content

Official SweetAlert2 enhancer adding support for React elements as content
MIT License
695 stars 47 forks source link

TypeError: (0 , sweetalert2_react_content_1.default) is not a function in Jest #183

Closed abtx closed 2 years ago

abtx commented 2 years ago

When running a Jest test I'm getting TypeError: (0 , sweetalert2_react_content_1.default) is not a function:

● Sweet alert modal › renders modal

    TypeError: (0 , sweetalert2_react_content_1.default) is not a function

      21 |
      22 | const Modal = (props: ModalProps) => {
    > 23 | const MySwal = withReactContent(Swal);
         |                                ^
      24 |   const openModal = useCallback((): void => {
      25 |     MySwal.fire({
      26 |       ...props.rest,

My imports look like this:

import Swal from "sweetalert2/dist/sweetalert2"; // this is because I want my own styles, but I'm getting the same error when using "sweetalert2"
import withReactContent from "sweetalert2-react-content"; 

I'm using Typescript in my project, and it seems that the typings aren't working properly, so I have declared custom module. If I remove the declaration, TS will complain when usng "sweetalert2/dist/sweetalert2" import:

TS2307: Cannot find module 'sweetalert2/dist/sweetalert2' or its corresponding type declarations.

TS doesn't complain about types when I import Swal using "sweetalert2", but the Jest error will happen anyway.

The Jest error is a type error and appears even when TS is happy about types, which is interesting, but I'm wondering whether they're related anyway?

abtx commented 2 years ago

I will answer my own problem. Adding "esModuleInterop": true, in tsconfig.json sorts out the issue with Jest (following Swal Webpack example).