browserify / browserify/sha.js

index.js exports overwrite exports in jest context

Open
#75 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
298
Forks
65
PR merge metrics
No merged PRs in 30d

Description

So I've been dealing with a strange error for the past week and I finally managed to pinpoint the issue.

My project has subdependency to this project through other third parties.

When I am testing the build with jest, my main exported class is undefined.

I've dived into jest code and what jest does is a transpile of my esm module back to commonjs to work with its internals.

To do so, it wraps the ESM module into a function that takes a few parameters as entry, and one of them is called `exports` within that function, and is a reference to `module.exports` as seen here: https://github.com/jestjs/jest/blob/main/packages/jest-runtime/src/index.ts#L1578

So now, as sha.js' code is added into my module, this bit (https://github.com/browserify/sha.js/blob/master/index.js#L1) is overwriting that higher level `exports` object, making my class unavailable for jest tests.

I have made a local patch with this interface rather:

```
const supportedAlgorithms = {};
module.exports = function SHA (algorithm) {
algorithm = algorithm.toLowerCase()

var Algorithm = supportedAlgorithms[algorithm]
if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')

return new Algorithm()
}

module.exports.sha = supportedAlgorithms.sha = require('./sha')
module.exports.sha1 = supportedAlgorithms.sha1 = require('./sha1')
module.exports.sha224 = supportedAlgorithms.sha224 = require('./sha224')
module.exports.sha256 = supportedAlgorithms.sha256 = require('./sha256')
module.exports.sha384 = supportedAlgorithms.sha384 = require('./sha384')
module.exports.sha512 = supportedAlgorithms.sha512 = require('./sha512')
```

And now my tests can retrieve my class and run as expected. It seems that the `exports` variable is only for simplicity and scope level check of support, so it wouldn't break consumption in my opinion.

I'm not sure what to do from there, I'd rather not make a fork (especially that this is not a first level dependency, so I'd have to make a dirtier hack in my package to ensure which version is consumed) but it also seems that this package does not get much attention these days. I'm happy to open a PR, but I would also like to have your feedback first, to find the best option for all of us.

Thanks for your support

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.