jedisct1 / libsodium.js

libsodium compiled to Webassembly and pure JavaScript, with convenient wrappers.
Other
968 stars 138 forks source link

Import error when importing libsodium-wrapper to a react-scripts-test unit test #336

Open AlexNi245 opened 4 months ago

AlexNi245 commented 4 months ago

Hello,

We've been working with libsodium-wrappers for a while, and it's an amazing library. We use it with functions in Node.js and React. Everything works fine when the libsodium-wrapper import is used within the app itself. However, we face some issues whenever we want to test anything that has a dependency on libsodium wrappers.

When I execute react-scripts test for the following code snippet.


import _sodium from 'libsodium-wrappers';

describe('sodium test', () => {
    it.only('test', async () => {
        await _sodium.ready;
        console.log('done');
        console.log(_sodium);
    });
});

I receive the following error

TypeError: Cannot read properties of undefined (reading 'sodium')

> 1 | import _sodium from 'libsodium-wrappers';
    | ^
  2 |
  3 | describe('useAuthTest', () => {
  4 |     beforeAll(async () => {});

  at ../../node_modules/libsodium-wrappers/dist/modules/libsodium-wrappers.js:1:83393
  at Object.<anonymous> (../../node_modules/libsodium-wrappers/dist/modules/libsodium-wrappers.js:1:83715)
  at Object.<anonymous> (src/hooks/auth/useAuth.test.ts:1:1)
  at TestScheduler.scheduleTests (../../node_modules/react-scripts/node_modules/@jest/core/build/TestScheduler.js:333:13)
  at runJest (../../node_modules/react-scripts/node_modules/@jest/core/build/runJest.js:404:19)
  at _run10000 (../../node_modules/react-scripts/node_modules/@jest/core/build/cli/index.js:320:7)
  at runCLI (../../node_modules/react-scripts/node_modules/@jest/core/build/cli/index.js:173:3)

It seems that there is a problem with importing the underlying sodium library. As I understand it, the asynchronous behavior of libsodium is the reason why you have to await with _sodium.ready in the first place. However, when executed within the unit test, the error occurs during the import process itself.

Do you have an idea how I could fix this issue?

Thanks for your help!

Test command : "test": "CI=true react-scripts test --transformIgnorePatterns \"node_modules/(?!dm3-lib-\\w*)/\""

Dependencies: "ibsodium-wrappers": "^0.7.11"

masonicboom commented 2 months ago

I had a similar error in Deno tests. I suspect the issue is that you're importing the library using ES Modules syntax (import) but the library is not packaged to support that. I'm working on ESM support at https://github.com/jedisct1/libsodium.js/pull/337. You could try the build steps in that PR and see if it fixes your issue