Installations
npm install babel-plugin-rewire-ts
Developer
rosswarren
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
No
Node Version
12.18.3
NPM Version
6.14.6
Statistics
11 Stars
296 Commits
6 Forks
3 Watching
1 Branches
36 Contributors
Updated on 23 Jun 2023
Bundle Size
23.09 kB
Minified
5.29 kB
Minified + Gzipped
Languages
JavaScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
4,349,347
Last day
-43.1%
1,206
Compared to previous day
Last week
-28.1%
7,990
Compared to previous week
Last month
2.8%
49,337
Compared to previous month
Last year
-46.7%
822,395
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dev Dependencies
33
babel-plugin-rewire-ts
This is a fork of https://github.com/speedskater/babel-plugin-rewire which adds TypeScript compatibility. I will happily accept any contributions which further improve the support.
A Babel plugin that adds the ability to rewire module dependencies.
It is inspired by rewire.js and transfers its concepts to es6 using babel.
It is useful for writing tests, specifically to mock the dependencies of the module under test.
Therefore for each module it adds and exports the methods __GetDependency__
, __Rewire__
, and __ResetDependency__
.
For compatibility reasons with rewire.js, the methods __get__
and __set__
are exported as well.
From version 1.0.0-rc-7 on calls to __set__
will return a revert function like rewire.js.
These methods allow you to rewire the module under test. Furthermore in case of a default export these methods are assigned to the existing default export, except for default exports of primitive types (boolean, number, string, ...).
An additional object named __RewireAPI__
is exported as named export as well as a property of the default export. This object itself contains all the functions mentioned above as fields. This enables one to rewire members of the imported module itself without explicitly importing the module (see Handling of default exports below).
ES6 Imports and React
Dependencies from import statements can be rewired
Example
1import ChildComponent from "child-component-module"; 2 3export default class MyFancyWrapperComponent extends React.Component { 4 render() { 5 return ( 6 <div className="wrapper-style"> 7 <ChildComponent {...this.props} /> 8 </div> 9 ); 10 } 11}
Test Code
1import ComponentToTest from 'my-fancy-wrapper-component-module'; 2 3ComponentToTest.__Rewire__('ChildComponent', React.createClass({ 4 render: function() { return <div {...this.props}></div>; } 5})); 6.... 7 8ComponentToTest.__ResetDependency__('ChildComponent');
Node/browserify require() and top-level var support
Variables declared and initialised at the top level, such as those from require() calls, can be rewired
Example
1var Path = require("path"); 2 3var env = "production"; 4 5module.exports = function(name) { 6 return Path.normalise(name); 7};
Test Code
1var Normaliser = require('Normaliser'); 2 3Normaliser.__Rewire__('Path', { 4 normalise: (name) => name; 5}); 6 7Normaliser.__Rewire__('env', 'testing'); 8.... 9 10Normaliser.__ResetDependency__('Path');
Named and top level function rewiring
Besides top level variables also top level functions defined in the imported module can be rewired.
When exported functions of a module depend on each other it can be convenient to test them independently. Hence, babel-plugin-rewire allows you to rewire the internal dependencies to exported named functions as shown in the example below.
Be aware, that rewiring a named export does not influence imports of that same export in other modules!
Example
Asuming you have a module TodoOperations.js
that internaly uses an asynchronous api to fetch some information
1function fetchToDos() { 2 ... 3 return new Promise(...); 4} 5 6export function filterToDos( filterString ) { 7 return fetchToDos().then( function( todos ) { 8 // Highly fashioned filter function code ... 9 return filteredToDos; 10 }); 11} 12 13export function filterAndSortToDos( filterString, sortOrder ) { 14 return fetchToDos( filterString ).then( function( filteredToDos ) { 15 // Higly fashioned sort function 16 return filteredAndSortedToDos; 17 }); 18}
Test Code
In your test you can mock your API-calls to simply return static dummy data like this
1import { filterToDos, filterAndSortToDos, __RewireAPI__ as ToDosRewireAPI } from "TodoOperations.js"; 2 3describe("api call mocking", function() { 4 it("should use the mocked api function", function(done) { 5 ToDosRewireAPI.__Rewire__("fetchToDos", function() { 6 return Promise.resolve(["Test more", "Refine your tests", "Tests first rocks"]); 7 }); 8 filterToDos("Test") 9 .then(function(filteredTodos) { 10 //check results 11 done(); 12 }) 13 .catch(e => fail()); 14 ToDosRewireAPI.__ResetDependency__("fetchToDos"); 15 }); 16 17 it("should use the mocked filter function", function(done) { 18 ToDosRewireAPI.__Rewire__("filterToDos", function() { 19 return Promise.resolve(["02 Test more", "01 Test even more"]); 20 }); 21 filterAndSortToDos("Test", "asc") 22 .then(function(filteredAndSortedTodos) { 23 //check results 24 done(); 25 }) 26 .catch(e => fail()); 27 ToDosRewireAPI.__ResetDependency__("filterToDos"); 28 }); 29});
Handling of default exports
If a non primitive default export is present in the imported module, it is enriched with the API-Functions and the API-Object.
If no default export is present, the API-Object named __RewireAPI__
becomes the default export of the module.
This object basically supports all the rewire API-Functions as described in the introduction above and allows one to rewire the module without explicitly importing the module itself.
Example
Asuming your imported module does not have a default export specified like in this simple example
1function message() { 2 return "Hello world"; 3} 4 5export function foo() { 6 return message(); 7}
Test Code
In your test you would use the default exported API-Object to rewire the function message
of the imported module like this
1import FooModule from "foo.js"; 2import { foo, __RewireAPI__ as FooModuleRewireAPI } from "foo.js"; 3 4describe("module default export test", function() { 5 it("should demonstrate the default exported rewire api", function() { 6 expect(foo()).to.equal("Hello world"); 7 FooModule.__Rewire__("message", function() { 8 return "my message"; 9 }); 10 expect(foo()).to.equal("my message"); 11 FooModule.__ResetDependency__("message"); 12 }); 13 14 it("should demonstrate the rewire apis named export", function() { 15 expect(foo()).to.equal("Hello world"); 16 FooModuleRewireAPI.__Rewire__("message", function() { 17 return "my message"; 18 }); 19 expect(foo()).to.equal("my message"); 20 FooModuleRewireAPI.__ResetDependency__("message"); 21 }); 22});
Handling of async functions
Rewiring of async functions works as one would expect using the same API as for other rewires for both default exports and named exports.
Example
Assuming your imported module consists of the following.
1// api.js 2export default async function asyncApiDefault() { 3 return await asyncApi(); 4} 5 6export async function asyncApi() { 7 return await api(); 8} 9 10function api() { 11 // Some async API call 12 return Promise.resolve("API Response"); 13}
Test Code
In your test you would use the default exported API-Object to rewire the function asyncApiDefault
and asyncApi
of the imported module like this.
1import { default as asyncApiDefault, asyncApi, __RewireAPI__ as AsyncApiRewireAPI } from "api.js"; 2describe("async function export test", function() { 3 it("should be able to rewire default async function", function() { 4 return asyncApiDefault().then(response => { 5 expect(response).to.equal("API Response"); 6 7 AsyncApiRewireAPI.__set__("asyncApi", function() { 8 return Promise.resolve("Mock API Response"); 9 }); 10 11 return asyncApiDefault().then(response => { 12 expect(response).to.equal("Mock API Response"); 13 AsyncApiRewireAPI.__ResetDependency__("asyncApi"); 14 }); 15 }); 16 }); 17 18 it("should be able to rewire non default async function", function() { 19 return asyncApi().then(response => { 20 expect(response).to.equal("API Response"); 21 22 AsyncApiRewireAPI.__set__("api", function() { 23 return Promise.resolve("Mock API Response"); 24 }); 25 26 return asyncApi().then(response => { 27 expect(response).to.equal("Mock API Response"); 28 AsyncApiRewireAPI.__ResetDependency__("api"); 29 }); 30 }); 31 }); 32});
Resetting all
When "babel-plugin-rewire" is used the global method __rewire_reset_all__
is added.
Each time this method is called all rewired dependencies across all modules are reset.
Example
Assuming you have two imported modules:
Module1:
1var value = "Module1-Original"; 2 3export default function getModule2Identifier() { 4 return value; 5}
Module2:
var value = 'Module2-Original';
export default function getModule2Identifier() {
return value;
}
Test Code
In your test by calling __rewire_reset_all__
all dependencies are reset and you can ensure that no rewired data will harm subsequent tests.
1import getModule1Identifier from "./src/Module1.js"; 2import getModule2Identifier from "./src/Module2.js"; 3 4import expect from "expect.js"; 5 6describe("__rewire_reset_all__", function() { 7 it("should allow to reset all rewired dependencies", function() { 8 expect(getModule1Identifier()).to.be("Module1-Original"); 9 expect(getModule2Identifier()).to.be("Module2-Original"); 10 11 getModule1Identifier.__set__("value", "module1-rewired"); 12 getModule2Identifier.__set__("value", "module2-rewired"); 13 14 expect(getModule1Identifier()).to.be("module1-rewired"); 15 expect(getModule2Identifier()).to.be("module2-rewired"); 16 17 __rewire_reset_all__(); 18 19 expect(getModule1Identifier()).to.be("Module1-Original"); 20 expect(getModule2Identifier()).to.be("Module2-Original"); 21 }); 22});
Installation
$ npm install babel-core babel-plugin-rewire
Usage
To use the plugin identify it by its long name "babel-plugin-rewire-ts" or by its abbreviation "rewire-ts".
If you are using @babel/plugin-tranform-typescript
and encounter these warnings:
The exported identifier "_get__" is not declared in Babel's scope tracker
as a JavaScript value binding, and "@babel/plugin-transform-typescript"
never encountered it as a TypeScript type declaration.
It will be treated as a JavaScript value.
...
We recommend you switch to @babel/preset-typescript
, since it type-checks
your code while the plugin does not. Or use @babel/preset-env
along with
the plugin to resolve those warnings. We already fixed the issue on our side
and reason behind those warning is unclear and they are harmless.
Commandline
abbreviated:
$ babel --plugins rewire ..
full plugin name:
$ babel --plugins babel-plugin-rewire ..
With babelrc
You can also specify plugins via the babelrc file:
1{ 2 "plugins": ["rewire"] 3}
Whether you're using the command line, JS API, or require hook, this file is honored by babel.
JavaScript API
abbreviated:
1require("babel-core").transform("code", { plugins: ["rewire"] });
full plugin name:
1require("babel-core").transform("code", { plugins: ["babel-plugin-rewire"] });
Require Hook
1require("babel-register")({ 2 plugins: ["babel-plugin-rewire"] 3});
Webpack
abbreviated:
1{test: /src\/js\/.+\.js$/, loader: 'babel-loader?plugins=rewire' }
full plugin name:
1{test: /src\/js\/.+\.js$/, loader: 'babel-loader?plugins=babel-plugin-rewire' }
Browserify/Babelify
full plugin name:
1var appBundler = browserify({ 2 entries: [test.src] // Only need initial file, browserify finds the rest 3}).transform( 4 babelify.configure({ 5 plugins: [require("babel-plugin-rewire")] 6 }) 7);
Combining with other plugins/tools
istanbul
To integrate babel-plugin-rewire with istanbul, it is recommended to use babel-plugin-istanbul. This babel plugin instruments your code with Istanbul coverage.
It has been reported that the order of plugins are important. Therefore prefer the following order:
1{ 2 "plugins": ["istanbul", "rewire"] 3}
For a project integrating karma, babel, babel-plugin-rewire and istanbul please see karma-rewire-istanbul-example
isparta
There are some things to consider when using babel-plugin-rewire together with isparta. Since isparta runs Babel itself it's important to remember to add the same configuration options to it as you would do with Babel. If you forget this you will in some cases see unexpected errors.
If you use .babelrc it's advised that you run your tests with a specific ENV, for example "test", and add the following to your .babelrc. Furthermore in case you use isparta only add the plugin once in the isparta loader and not in the babel loader as well.
1"env": { 2 "test": { 3 "plugins": ["rewire"] 4 } 5}
If you are using isparta together with Webpack you could also do something like this.
1webpack: { 2 isparta: { 3 embedSource: true, 4 noAutoWrap: true, 5 babel: { 6 plugins: 'rewire' 7 } 8 }, 9 preLoaders: [ 10 ... 11 { 12 test: /\.js$/, 13 include: path.resolve('src/'), //only source under test 14 loader: 'isparta' 15 }, 16 ] 17 ... 18}
Examples projects
Release History
- 0.1.0 Initial release
- 0.1.1 Bugfix: moved to peer dependencies
- 0.1.2 Added __set__ and __get__ to provide compatibility with rewire.js
- 0.1.3 Added handling for the export of named declarations like classes or functions
- 0.1.4 Fixed variable handling and used renaming of scope variables. Further removed global identifiers to prevent memory leaks.
- 0.1.5 Fixed regression
- 0.1.6 Support for rewiring top level variables. Added module.exports for non-es6 modules.
- 0.1.7 Fixed regressions from 0.1.6.
- 0.1.8 Ignores destructuring assignments to prevent errors.
- 0.1.9 Removed issues with TDZ and es6.spec.blockScoping optional transformer.
- 0.1.10 Fixed tests.
- 0.1.11 Fixed issues with for-of loops.
- 0.1.12 Updated Plugin Format.
- 0.1.13 Changed rewire specific properties on default export to non-enumerable properties.
- 0.1.14 Added handling for non-enumerable properties to commonjs support. Support for mixed es6 and commonjs support. Handling for primitive types.
- 0.1.15 Added functionality to rewire functions.
- 0.1.16 Fixed variable scope for rewired functions.
- 0.1.17 Fixed variable scoping for var variable declarations.
- 0.1.18 Fixed function scope for rewired functions.
- 0.1.19 Removed debug statements.
- 0.1.20 Added rewiring named exported functions and variables.
- 0.1.21 Improved default export handling, fixed commonjs default exporting, fixed ast nodes resource leaks, improved README.
- 0.1.22 Added support for asynchronous functions
- 0.1.23-beta Improved flow compatibility, Added functionality to work with cyclic dependencies.
- 1.0.0-beta-1 Added support for babel 6, added support for rewiring classes, added support for flow types, added support for rewire.js compatible __with__
- 1.0.0-beta-2 Removed rewire of Object, require
- 1.0.0-beta-3 Removed support for rewiring of globals. Added support for rewiring in combination with assignment and update expressions.
- 1.0.0-beta-4 Updates jsx support in combination with babel 6 but has a regression
- 1.0.0-beta-5 Fixes rewiring of jsx elements. Readme improvements. Test for pass-through like modules.
- 1.0.0-rc-1 Fixes rewiring of switch statements. Readme improvements. Wildcard imports and tdz issues.
- 1.0.0-rc-2 Fixes issues with babelify, React stateless functions as well as flow declarations.
- 1.0.0-rc-3 Added support for ignoring identifiers and support for objects as parameter to __set__
- 1.0.0-rc-4 Support for rewiring to undefined, suppport for should.js and cleaned up package.json.
- 1.0.0-rc-5 Improved support for rewiring JSX-Components. Further improved for working in combination with other plugins.
- 1.0.0-rc-6 Fixed regression which can occur with variable declarators and function expressions. Fixed handling of default exports containing nested functions.
- 1.0.0-rc-7 Added revert function as a return of __set__ calls.
- 1.0.0 Fixed regression with object methods and improved istanbul documentation.
- 1.2.0-rc.1 Add support for babel 7, object spread and revert function from __set__ with object and fixes undefined variable error
Contributors
- speedskater - author and creator of initial release
- Peet - module.exports and top-level var support
- TheSavior - support for non-enumerable rewire properties, support for ignored identifiers
- Rene Saarsoo - support for using objects as parameter to __set__
- PSpSynedra - support for named export and function rewiring and improvements of default imports
- Gustaf Dalemar - support for asynchronous functions
- Spencre Leichty - support for named wildcard exports
- Zhanzhan He - support for wildcard imports
- Kelly Selden - fixed dependencies in package.json
- Sasha Koss - support for rewiring to undefined
- Kevin Canévet - fixed incompatibility with should
- Mike Sherov - added support for for in loops
- Thomas Levy - added support for babel 7
- Malthe Jørgensen - added support for object spread
- Tim Whitbeck - added revert function from __set__ with object
- Dennis E - fixed undefined __$$GLOBAL_REWIRE_REGISTRY__ error
License
The ISC License (ISC)
Copyright (c) 2015, Robert Binna r.binna@synedra.com
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
Found 3/22 approved changesets -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/rewire-ts.yml:1
- Info: no jobLevel write permissions found
Reason
project is archived
Details
- Warn: Repository is archived.
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/rewire-ts.yml:23: update your workflow using https://app.stepsecurity.io/secureworkflow/rosswarren/babel-plugin-rewire-ts/rewire-ts.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/rewire-ts.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/rosswarren/babel-plugin-rewire-ts/rewire-ts.yml/master?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/rewire-ts.yml:28
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
license file not detected
Details
- Warn: project does not have a license file
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 13 are checked with a SAST tool
Reason
24 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-cwfw-4gq5-mrqx
- Warn: Project is vulnerable to: GHSA-g95f-p29q-9xw4
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-9vvw-cc9w-f27h
- Warn: Project is vulnerable to: GHSA-gxpj-cx7g-858c
- Warn: Project is vulnerable to: GHSA-w573-4hg7-7wgq
- Warn: Project is vulnerable to: GHSA-h6ch-v84p-w6p9
- Warn: Project is vulnerable to: GHSA-qh2h-chj9-jffq
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-29mw-wpgm-hmr9
- Warn: Project is vulnerable to: GHSA-35jh-r3h4-6jhm
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-hxm2-r34f-qmc5
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-vh95-rmgr-6w4m / GHSA-xvch-5gv4-984h
- Warn: Project is vulnerable to: GHSA-w9mr-4mfr-499f
- Warn: Project is vulnerable to: GHSA-r683-j2x4-v87g
- Warn: Project is vulnerable to: GHSA-662x-fhqg-9p8v
- Warn: Project is vulnerable to: GHSA-394c-5j6w-4xmx
- Warn: Project is vulnerable to: GHSA-78cj-fxph-m83p
- Warn: Project is vulnerable to: GHSA-fhg7-m89q-25r3
- Warn: Project is vulnerable to: GHSA-c4w7-xm78-47vh
Score
2.3
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to babel-plugin-rewire-ts
@juanger/babel-plugin-rewire-ts
A babel plugin adding the ability to rewire module dependencies. This enables to mock modules for testing purposes.
babel-plugin-rewire
A babel plugin adding the ability to rewire module dependencies. This enables to mock modules for testing purposes.
babel-plugin-rewire-exports
Babel plugin for stubbing (ES6, ES2015) module exports
@babel/helper-plugin-utils
General utilities for plugins to use