Prechádzať zdrojové kódy

Allow sandboxed-module for model mockery

GitOrigin-RevId: 79dfe75088b760968fdc1b6e5dce4278f44a0dae
Andrew Rumble 9 mesiacov pred
rodič
commit
0fdd87f345

+ 19 - 0
services/web/test/unit/src/helpers/indirectlyImportModels.js

@@ -0,0 +1,19 @@
+// When importing models in vitest unit tests we need to import them from a CJS file
+// instead of directly from the test file so that we can mock the model when it is imported via CJS
+// and make sure that is in the require cache for other imports.
+//
+// TODO: This helper can be removed when all models are converted to ESM and vitest can handle them correctly.
+
+/**
+ *
+ * @param {string[]} models
+ */
+module.exports = function (models) {
+  return models.reduce((exports, model) => {
+    const module = require(`./models/${model}`)
+    return {
+      ...exports,
+      ...module,
+    }
+  }, {})
+}

+ 29 - 0
services/web/test/unit/vitest_bootstrap.mjs

@@ -4,6 +4,35 @@ import sinon from 'sinon'
 import logger from '@overleaf/logger'
 import sinonChai from 'sinon-chai'
 import chaiAsPromised from 'chai-as-promised'
+import SandboxedModule from 'sandboxed-module'
+import { createRequire } from 'module'
+
+const require = createRequire(import.meta.url)
+
+SandboxedModule.configure({
+  ignoreMissing: true,
+  requires: {
+    // This is already imported the same way in the mocha bootstrap
+    // eslint-disable-next-line import/no-extraneous-dependencies
+    sshpk: require('sshpk'),
+  },
+  globals: {
+    AbortController,
+    AbortSignal,
+    Buffer,
+    Promise,
+    console,
+    process,
+    URL,
+    TextEncoder,
+    TextDecoder,
+  },
+  sourceTransformers: {
+    removeNodePrefix: function (source) {
+      return source.replace(/require\(['"]node:/g, "require('")
+    },
+  },
+})
 
 /*
  * Chai configuration