follow-redirects: Dynamic loading of debug possibly incompatible with Jest

I am encountering this error in my test suite using nock 12.0.3 and axios 0.21.1. It seems to be intermittent as well.

TypeError: Cannot read property 'apply' of undefined
        at module.exports (/Users/brian.moran/repos/subscription-service/node_modules/follow-redirects/debug.js:15:9)
        at Object.request (/Users/brian.moran/repos/subscription-service/node_modules/follow-redirects/index.js:457:7)
        at dispatchHttpRequest (/Users/brian.moran/repos/subscription-service/node_modules/axios/lib/adapters/http.js:195:25)
        at new Promise (<anonymous>)
        at httpAdapter (/Users/brian.moran/repos/subscription-service/node_modules/axios/lib/adapters/http.js:46:10)
        at dispatchRequest (/Users/brian.moran/repos/subscription-service/node_modules/axios/lib/core/dispatchRequest.js:52:10)

I am able to “fix” the issue by adding if(debug === undefined) return; to debug.js

var debug;

module.exports = function () {
  if (!debug) {
    try {
      /* eslint global-require: off */
      debug = require("debug")("follow-redirects");
    }
    catch (error) {
      debug = function () { /* */ };
    }
  }
  
  // "fixes" TypeError: Cannot read property 'apply' of undefined 
  if(debug === undefined) return;
  debug.apply(null, arguments);
};

Is this a known issue or is perhaps my problem elsewhere?

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 3
  • Comments: 15 (2 by maintainers)

Commits related to this issue

Most upvoted comments

For those curious, I may have solved this incorrectly. It seems the root cause is the fact the file is named debug.js and it is running in jest. If you set a breakpoint right after the require statement, debug is undefined (the core issue). However, doing this:

require.resolve('debug')
Uncaught RangeError: Maximum call stack size exceeded

Apparently (and I’m just learning this), naming your module debug and requiring a module named debug is not supported. To test, I renamed the old file follow-debug.js and the problem is solved.

I’m not sure this warrants changing the fix, but I’m posting here for posterity

it’s Jest related

It probably is. That’s the insight we needed! Jest does some magic hoisting.