swc-project / swc

Rust-based platform for the Web
https://swc.rs
Apache License 2.0
30.93k stars 1.21k forks source link

provide a way to avoid having to specify __esModule:true in jest.mock() #9482

Open dalimian opened 3 weeks ago

dalimian commented 3 weeks ago

Describe the feature

after migrating jest from babel to swc we found that now our unit tests have to specify an __esModule: true when mocking a module that has a default export.

example:

jest.mock('path/to/some-module.js', () => ({
 default: jest.fn(),
 __esModule: true,
}));

worth a mention that it seems this is only needed when mocking a module that is dynamically imported with import() (statically imported modules are fine)

we previously avoided this with babel config via specifying a noInterop: true on a plugin called babel-plugin-dynamic-import-node

here is the full Babel config

{
  "presets": [
    ["@babel/preset-env", {
      "exclude": ["proposal-dynamic-import"]
    }],
    "@babel/preset-react"
  ],
  "plugins": [
    ["babel-plugin-dynamic-import-node", { "noInterop": true }],
    "@babel/plugin-transform-runtime",
    ["babel-plugin-module-resolver", {
      "root": ["."]
      }
    }]
  ]
}

can you please provide an equivalent for swc config

our swc config is

{
  "$schema": "https://swc.rs/schema.json",
  "sourceMaps": "inline",
  "jsc": {
    "target": "es5",
    "externalHelpers": true,
    "loose": true,
    "baseUrl": "./",
    "parser": {
      "syntax": "ecmascript",
      "jsx": true,
      "dynamicImport": true
    },
    "transform": {
      "react": {
        "pragma": "React.createElement",
        "pragmaFrag": "React.Fragment",
        "throwIfNamespace": true,
        "development": false,
        "useBuiltins": false
      },
      "optimizer": {
        "globals": {
          "vars": {
            "NODE_ENV": "true"
          }
        }
      }
    },
    "experimental": {
      "plugins": [
        [
          "swc_mut_cjs_exports",
          {}
        ]
      ]
    }
  },
  "module": {
    "type": "commonjs"
  }
}

Babel plugin or link to the feature description

No response

Additional context

No response

kdy1 commented 3 weeks ago

You may try noInterop: true for swc

kdy1 commented 3 weeks ago

And please provide a minimal reproduction

dalimian commented 2 weeks ago

thanks @kdy1 , here is github and codesandbox links that minimally reproduce the issue, whichever you prefer

I did try noInterop: true, it did fix this issue but introduced another issue where nothing from node_modules could be imported, links above reproduce that as well