https://github.com/nktnet1/jewire
Access private functions, variables and classes from CommonJS modules . Enable named exports with relative paths identical to CommonJS require. Clone objects at runtime to remove false negatives in expect.toStrictEqual
https://github.com/nktnet1/jewire
dependency fake hidden import jest mock modules private require rewire test unit
Last synced: 3 months ago
JSON representation
Access private functions, variables and classes from CommonJS modules . Enable named exports with relative paths identical to CommonJS require. Clone objects at runtime to remove false negatives in expect.toStrictEqual
- Host: GitHub
- URL: https://github.com/nktnet1/jewire
- Owner: nktnet1
- License: mit
- Created: 2023-10-09T10:36:27.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2025-01-28T14:48:17.000Z (over 1 year ago)
- Last Synced: 2025-04-15T14:14:24.804Z (about 1 year ago)
- Topics: dependency, fake, hidden, import, jest, mock, modules, private, require, rewire, test, unit
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/jewire
- Size: 790 KB
- Stars: 2
- Watchers: 1
- Forks: 1
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# [](https://github.com/nktnet1/jewire)
[](https://github.com/nktnet1/jewire/actions/workflows/pipeline.yml)
[](https://codecov.io/gh/nktnet1/jewire)
[](https://codeclimate.com/github/nktnet1/jewire/maintainability)
[](https://snyk.io/test/github/nktnet1/jewire)
[](https://github.com/search?q=repo%3Anktnet1%2Fjewire++language%3ATypeScript&type=code)
[](https://www.npmjs.com/package/jewire?activeTab=versions)
[](https://packagephobia.com/result?p=jewire)
[](https://depfu.com/github/nktnet1/jewire?project_id=39032)
[](https://app.fossa.com/projects/git%2Bgithub.com%2Fnktnet1%2Fjewire?ref=badge_shield)
[](https://opensource.org/license/mit/)
[](https://github.com/nktnet1/jewire/issues)
[](https://sonarcloud.io/summary/new_code?id=nktnet1_jewire)
[](https://app.codacy.com/gh/nktnet1/jewire/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade)
[](https://app.deepsource.com/gh/nktnet1/jewire/)
[](https://codebeat.co/projects/github-com-nktnet1-jewire-main)
[](https://github.com/nktnet1/jewire/stargazers)
[](https://moiva.io/?npm=jewire)
[](https://moiva.io/?npm=jewire)
[](https://moiva.io/?npm=jewire)
[](https://moiva.io/?npm=jewire)
[](https://moiva.io/?npm=jewire)
---
Access private functions, variables and classes from CommonJS modules
Enable named exports with relative paths identical to CommonJS [require](https://nodejs.org/api/modules.html#requireid)
Clone objects at runtime to remove false negatives in expect[.toStrictEqual](https://jestjs.io/docs/expect#tostrictequalvalue)
[](https://replit.com/@nktnet1/jewire-example#index.js)
---
- [1. Installation](#1-installation)
- [2. Usage](#2-usage)
- [2.1. relativePath](#21-relativepath)
- [2.2. options](#22-options)
- [2.3. return](#23-return)
- [3. License](#3-license)
- [4. Limitations](#4-limitations)
- [5. Caveats](#5-caveats)
- [5.1. Purpose](#51-purpose)
- [5.2. Rationale](#52-rationale)
- [5.3. Rewire and Jest](#53-rewire-and-jest)
## 1. Installation
```
npm install jewire
```
## 2. Usage
Try with [Replit](https://replit.com/@nktnet1/jewire-example#index.js).
```
jewire(relativePath, options);
```
Examples (click to view)
Importing from the same directory
```javascript
const { privateVariable, privateFunction } = jewire('private-module');
```
Importing `.cjs` file from a different directory
```javascript
const { privateFunction } = jewire('../src/private-module.cjs');
```
Using a different basePath
```javascript
const { privateFunction } = jewire(
'private-module',
{ basePath: process.cwd() }
);
```
Using a different clone function from the default `clone.objectClone`:
```javascript
const { privateFunction } = jewire(
'private-module',
{ objectClone: (obj) => JSON.parse(JSON.stringify(obj)) }
);
```
### 2.1. Parameter: relativePath
Path to the module relative to the current file, similar to CommonJS [require](https://nodejs.org/api/modules.html#requireid). For example,
- `'../animals/cats.js'`
- `'./common.cjs'`
- `'minimal'`
- `jewire` will look for `'./minimal.js'` before `'./minimal.cjs'`
Note that `option.basePath` can be provided to alter this behaviour.
### 2.2. Parameter: options
Option
Description
Example
Default
basePath
Absolute path to the module's directory
process.cwd()
__dirname
objectClone
Cloning function to apply to any objects or arrays that are global symbols, function return values or class method return values.
o => JSON.parse(
JSON.stringify(
o
)
)
objectClone
(see clone.ts)
### 2.3. Return Object
All named exports, including globally defined variables, functions and classes are returned as keys within an object.
Additionally, the returned object contains the key `__jewireContext__` with the values being another object with the following properties:
1. `rewire`: the return value of `rewire(modulePath)`. Please refer to the documentation for [rewire](https://github.com/jhnns/rewire) for further details.
2. `hiddenExportInfo`: An object containing information about all hidden exports, of the form:
```javascript
{
symbols: {
variables: string[],
functions: string[],
classes: string[],
}
ast: ASTProgram, // Abstract Syntax Tree from Meriyah parser
code: string, // return value of fs.readFileSync(filePath)
}
```
3. `jewireGetter`: the internal function used by jewire to retrieve objects. It has the same prototype as [`rewireModule.__get__`](https://github.com/jhnns/rewire?tab=readme-ov-file#rewiredmodule__get__name-string-), although objects are deep cloned using either jewire's default clone function or, if provided, `options.objectClone`.
### 2.4. Errors
If an unknown file path is provided, the given file is empty or the module contains invalid code such as syntax errors, a default [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error) object is thrown.
## 3. License
Massachusetts Institute of Technology
(MIT)
```
Copyright (c) 2023 Khiet Tam Nguyen
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
```
[](https://app.fossa.com/projects/git%2Bgithub.com%2Fnktnet1%2Fjewire?ref=badge_large)
## 4. Limitations
As this library uses [rewire](https://github.com/jhnns/rewire) under the hood,
it has the same limitations in that it can only import CommonJS modules. Please
see the [limitations](https://github.com/jhnns/rewire#limitations) as described
in the rewire module.
## 5. Caveats
### 5.1. Purpose
**jewire** is a niche library designed to automark private functions in the
submitted code of students using the Jest testing framework during the first
2 weeks of their studies in
[COMP1531 Software Engineering Fundamentals](https://webcms3.cse.unsw.edu.au/COMP1531/23T2/outline).
This is because `npm` and module imports/exports are not introduced until week
3, when students are considered to be more familiar with JavaScript as a
programming language.
### 5.2. Rationale
**jewire** aims to simplify the process of using
[rewire](https://github.com/jhnns/rewire)
by removing the need to provide a file extension and absolute path, abstracting
getter and setter methods and enabling relative module imports similar to CommonJS
[require](https://nodejs.org/api/modules.html).
This process requires reading the module twice - once to parse into an [Abstract Syntax Tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree) using the [Meriyah](https://github.com/meriyah/meriyah) parser, and another from rewire as rewire's interface does not enable reusing the file content.
### 5.3. Rewire and Jest
**Jewire** reclones objects at runtime to allow the return values of rewired
functions and class methods to be compared using
[Jest](https://jestjs.io)'s
expect[.toStrictEqual](https://jestjs.io/docs/expect#tostrictequalvalue) matcher,
which in the rewire module would yield *"Received: serializes to the same
string"*.
The cause is Jest's utilisation of `node:vm` under the hood, which creates its own temporary context that overrides global classes such as `Array`, `Error` and `Date` to extend functionalities. These global classes differ from those that are returned from [rewire](https://github.com/jhnns/rewire)'s private functions, as depicted in the following GitHub issues made by [@geogezlei](https://github.com/georgezlei):
- https://github.com/jhnns/rewire/issues/164
- https://github.com/jestjs/jest/issues/8446
For further details and explanation about this problem, please visit Manuel Spigolon's [article](https://backend.cafe/should-you-use-jest-as-a-testing-library) about the use of the `instanceof` operator in Jest.