How to fix parent context unavailable when using proxyquire with ES6 import statement?

359 Views Asked by At

I have the following file to test which is the migration_repository.js

import {getDatabaseName}  from "./maria_db_connector"

export default class MigrationRepository {
    getExistingVersions() {
        return getDatabaseName();
    }

I am trying to mock the following module maria_db_connector.js:

export function getDatabaseName() {
    return process.env.KOA_DATASOURCE_DATABASE;
}

and the following test file:

import MigrationRepository from './migration_repository.js'
import proxyquire from 'proxyquire';
const proxy = proxyquire.noCallThru(); 

describe('MigrationRepository', function () {

  beforeEach(function () {
    proxy.load('./migration_repository.js', {
      './maria_db_connector.js': {
        getDatabaseName: function () { return "test" },
      }
    })
  });
}

However, when I run this test with mocha using the following command mocha *spec.js I see it is failing in proxyquire on the following line in the load function

  return this._withoutCache(this._parent, stubs, request, this._parent.require.bind(this._parent, request))

With the error message

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

For added context I have the following devDependencies

  "devDependencies": {
    "mocha": "^10.2.0",
    "proxyquire": "^2.1.3",
    "sinon": "^15.0.2"
  }

and I using node v18.15.0

So how do I populate the parent context with ES6 import statements?

0

There are 0 best solutions below