Esm: Unable to mock dynamic import

Created on 29 Apr 2018  路  5Comments  路  Source: standard-things/esm

Hi.

After I failed with proxyquire and mock-require I tried to narrow down the issue:

import Module from 'module'

const originalLoad = Module._load

Module._load = (request, ...rest) => {
  if (request === 'target') {
    console.log('!!!')

    return {}
  }

  return originalLoad(request, ...rest)
}

import('target').catch(console.error)
{ Error: Cannot find module 'target'
    at module.exports.t.a (node_modules/esm/esm.js:1:160550)
    at node_modules/esm/esm.js:1:113726
    at module.exports.t.a (node_modules/esm/esm.js:1:113805)
    at module.exports.t.a (node_modules/esm/esm.js:1:134550)
    at I (node_modules/esm/esm.js:1:179469)
    at Immediate._onImmediate (node_modules/esm/esm.js:1:178466)
    at runCallback (timers.js:794:20)
    at tryOnImmediate (timers.js:752:5)
    at processImmediate [as _immediateCallback] (timers.js:729:5) code: 'MODULE_NOT_FOUND' }

It feels like esm is somehow checking for module existence by itself before it goes to Module._load or something. Totally not sure about the internal mechanics, but it works fine if I use plain CJS require instead of dynamic import.

enhancement

Most helpful comment

Hi @deepsweet!

I can totally support this.

All 5 comments

Hi @deepsweet!

I can totally support this.

Oh. Please do, if it's really doable :) Going to face a lot of dynamic imports mocking in tests since I loved esm loader.

I've just added a scenario test to ensure mock-require and require-inject work with esm.
_(at the same time even)_ 馃槻馃槑

Update:

v3.0.29 is released 馃帀

FWIW For anyone else that finds this when looking for a mocking solution I found the package mocku https://www.npmjs.com/package/mocku very simple to setup and use.

It works a lot like the requireInject example above but I got it working first time vs struggling with the documentation of require-inject.

I like that esm is first class for mocku, although mocku is a very new library at this stage.

It's written by me in the wake of all the mocking related issues I've reported and jdalton has fixed 馃榿 Glad you found it useful.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

OmgImAlexis picture OmgImAlexis  路  3Comments

Pokute picture Pokute  路  3Comments

pvdlg picture pvdlg  路  3Comments

MVSICA-FICTA picture MVSICA-FICTA  路  3Comments

deepsweet picture deepsweet  路  3Comments