{"id":19103,"library":"babel-plugin-mockable-imports","title":"babel-plugin-mockable-imports","description":"A Babel plugin that transforms JavaScript/TypeScript modules to enable mocking of ES imports in tests. Current stable version is 2.0.1. It works with any test runner, bundler, and environment (Node or browser). Unlike tools like proxyquire or rewire, it operates at the Babel AST level, making it compatible with modern ES module syntax. The plugin detects incorrect usage (e.g., mocking non-existent imports) and is designed to minimize runtime overhead. It supports both JavaScript and TypeScript, and can be selectively enabled via Babel's env configuration.","status":"active","version":"2.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/robertknight/babel-plugin-mockable-imports","tags":["javascript","mocking"],"install":[{"cmd":"npm install babel-plugin-mockable-imports","lang":"bash","label":"npm"},{"cmd":"yarn add babel-plugin-mockable-imports","lang":"bash","label":"yarn"},{"cmd":"pnpm add babel-plugin-mockable-imports","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required as a peer dependency for Babel plugin functionality.","package":"@babel/core","optional":true}],"imports":[{"note":"Plugin is typically used in .babelrc or babel.config.js via require. Not directly imported in application code.","wrong":"No default import; must use CommonJS require in Babel config.","symbol":"default (plugin)","correct":"module.exports = require('babel-plugin-mockable-imports');"},{"note":"$imports is a runtime object injected by the plugin into transformed modules. Use named import in ESM.","wrong":"const $imports = require('./module').$imports;","symbol":"$imports","correct":"import { $imports } from './module';"},{"note":"$mock expects a single object mapping module paths to mock exports. For default exports, pass a function directly as the value.","wrong":"$imports.$mock('module-name', { exportName: mockValue });","symbol":"$mock","correct":"$imports.$mock({ 'module-name': { exportName: mockValue } });"},{"note":"Restores all previously set mocks. Accepts an optional argument to selectively restore specific modules.","wrong":"$restore();","symbol":"$restore","correct":"$imports.$restore();"}],"quickstart":{"code":"// Install: npm install --save-dev babel-plugin-mockable-imports\n// .babelrc\n{\n  \"env\": {\n    \"test\": {\n      \"plugins\": [\"mockable-imports\"]\n    }\n  }\n}\n\n// password.js (module under test)\nimport {randomBytes} from 'crypto-functions';\nexport function generatePassword() {\n  return randomBytes(10)\n    .map(byte => byte.toString(16).padStart(2, '0'))\n    .join('');\n}\n\n// password.test.js\nimport {generatePassword, $imports} from './password';\n\nafterEach(() => {\n  $imports.$restore();\n});\n\nit('generates expected password', () => {\n  const fakeRandomBytes = length => Array(length).fill(42);\n  $imports.$mock({\n    'crypto-functions': {\n      randomBytes: fakeRandomBytes,\n    },\n  });\n  expect(generatePassword()).toBe('2a2a2a2a2a2a2a2a2a2a');\n});","lang":"javascript","description":"Shows installation, Babel config, usage of $imports.$mock and $imports.$restore in a test."},"warnings":[{"fix":"Switch to Node >=12.17 or use ESM-compatible tooling. For backward compatibility, stick with v1.x.","message":"v2.0.0 converted the plugin and its runtime helpers to ES modules. If you use CommonJS-based tooling (e.g., older Node versions, or require() in Babel config), the plugin will not work. You must ensure your environment supports ESM, or use v1.x.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Use Babel's env configuration or conditional builds to only include the plugin for test/development environments.","message":"This plugin should only be applied in test or development builds. Applying it in production will cause performance overhead and leak the $imports object.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure the plugin is applied to all modules you want to mock. Use include/exclude options in Babel config.","message":"The $imports object is exported from transformed modules. If you import from a module that hasn't been transformed (e.g., node_modules), $imports will not exist and importing it will cause a runtime error.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If you use excludeImportsFromModules, provide a RegExp object instead of a string.","message":"In v1.8.0, excludeImportsFromModules was updated to support regex patterns. The previous string-only patterns may not work as expected.","severity":"deprecated","affected_versions":">=1.8.0"},{"fix":"Double-check that the export names you pass to $mock match exactly what the module exports.","message":"When mocking a module, if you specify an export name that does not exist in the original module, the plugin will report a runtime error. This is by design but can catch developers off-guard.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-25T00:00:00.000Z","next_check":"2026-07-24T00:00:00.000Z","problems":[{"fix":"Verify the plugin is enabled in your Babel config and that the module is being processed. Check if the module is excluded via exclude or include patterns.","cause":"The module has not been transformed by the plugin, or the plugin is not applied.","error":"$imports is not defined"},{"fix":"Run `npm install --save-dev babel-plugin-mockable-imports` and ensure your Babel config file is in the project root.","cause":"The plugin is not installed or not in the correct Babel plugins directory.","error":"Cannot find module 'babel-plugin-mockable-imports'"},{"fix":"Ensure @babel/core is installed: `npm install --save-dev @babel/core`. Check that the version matches the plugin requirements.","cause":"Incompatible version of @babel/core or missing peer dependency.","error":"Error: Plugin \"mockable-imports\" could not be loaded from \"@babel/core\"."},{"fix":"Import $imports from the specific module under test, not from a shared module. Check that the module is transformed.","cause":"The $imports object exists but is not the expected one (e.g., imported from a module that does not use the plugin).","error":"Uncaught TypeError: $imports.$mock is not a function"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}