TBD54566975 / bundler-bonanza

4 stars 4 forks source link

Writing Jest tests for client side Web5 #4

Open dayhaysoos opened 1 year ago

dayhaysoos commented 1 year ago

Hey! Not sure how relevant this is but wanted to share anyway.

I was tasked with writing some tests for the docusaurus site. These tests are supposed to protect us from breaking changes in the documentation site.

I am testing the functions that are being called in the quickstart.js file. I was running across a bunch environmental stuff.

Since I am testing the browser export of Web5, I needed to create a jest set up config to import some of the native browser APIs.

// needed to install a fake-indexddb
const fakeIndexedDB = require("fake-indexeddb");

// added it to the global scope
global.indexedDB = fakeIndexedDB.default;
global.TextEncoder = require("util").TextEncoder;

// needed to set this up for crytpo digest mock
global.self = global.self || {};

jest.setTimeout(10000);

Object.defineProperty(global.self, "crypto", {
  value: {
    subtle: {
      digest: jest.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4])),
    },
    getRandomValues: function (buffer) {
      let len = buffer.length;
      while (len--) {
        buffer[len] = Math.floor(Math.random() * 256);
      }
      return buffer;
    },
  },
  writable: true,
  configurable: true,
});

// add node-fetch to global scope
(async () => {
  const nodeFetch = await import("node-fetch");
  global.fetch = nodeFetch.default || nodeFetch;
})();

I am now running a test to create a did, however I get this error:

Cannot find module '@ipld/dag-cbor' from 'node_modules/.pnpm/@tbd54566975+dwn-sdk-js@0.0.35/node_modules/@tbd54566975/dwn-sdk-js/dist/cjs/src/utils/cid.js'

I'm still in the middle of troubleshooting this, but would like to know your thoughts if you have any.

dayhaysoos commented 1 year ago

Updating:

I think I found a way to address this, however, it's a very messy solution.

I've had to address each library it can't find like this:

{
  moduleNameMapper: {
    "^@ipld/dag-cbor$": "<rootDir>/node_modules/@ipld/dag-cbor/src/index.js",
    "^multiformats/cid$":
      "<rootDir>/node_modules/.pnpm/multiformats@12.0.1/node_modules/multiformats/src/cid.js",
    "^ipfs-unixfs-importer$":
      "<rootDir>/node_modules/.pnpm/ipfs-unixfs-importer@15.1.5/node_modules/ipfs-unixfs-importer/src/index.ts",
    "^it-first$":
      "<rootDir>/node_modules/.pnpm/it-first@3.0.2/node_modules/it-first/src/index.ts",
    "^it-parallel-batch$":
      "<rootDir>/node_modules/.pnpm/it-parallel-batch@3.0.1/node_modules/it-batch/src/index.ts",
  },

I was going down the list and after each time I added a new map, a new one came up. I gave up realizing I'd have to do this for tons of libraries and at the end of the day, I'm not 100% sure this would work in the end after all.

leordev commented 9 months ago

@dayhaysoos do you think it's still relevant or should we close?