npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

jewire

v3.0.0

Published

Rewire private modules for use within Jest.

Downloads

196

Readme

Jewire

pipeline   codecov   Maintainability   Snyk Security   GitHub top language

NPM Version   install size   Depfu Dependencies   FOSSA Status   NPM License   GitHub issues

Quality Gate Status   Codacy Badge   DeepSource   codebeat badge   GitHub stars

Downloads Total   Downloads Yearly   Downloads Monthly   Downloads Weekly   Downloads Daily


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

Try with Replit


1. Installation

npm install jewire

2. Usage

Try with Replit.

jewire(relativePath, options);

Importing from the same directory

const { privateVariable, privateFunction } = jewire('private-module');

Importing .cjs file from a different directory

const { privateFunction  } = jewire('../src/private-module.cjs');

Using a different basePath

const { privateFunction } = jewire(
  'private-module',
  { basePath: process.cwd() }
);

Using a different clone function from the default clone.objectClone:

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. 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

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 for further details.

  2. hiddenExportInfo: An object containing information about all hidden exports, of the form:

    {
      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__, 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 object is thrown.

3. License

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.

FOSSA Status

4. Limitations

As this library uses rewire under the hood, it has the same limitations in that it can only import CommonJS modules. Please see the 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.

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 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.

This process requires reading the module twice - once to parse into an Abstract Syntax Tree using the 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's expect.toStrictEqual 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's private functions, as depicted in the following GitHub issues made by @geogezlei:

  • 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 about the use of the instanceof operator in Jest.