How can I mock Webpack's require.context in Jest?

前端 未结 8 792
执念已碎
执念已碎 2020-12-08 09:38

Suppose I have the following module:

var modulesReq = require.context(\'.\', false, /\\.js$/);
modulesReq.keys().forEach(function(module) {
  modulesReq(modu         


        
8条回答
  •  隐瞒了意图╮
    2020-12-08 10:23

    Alrighty! I had major issues with this and managed to come to a solution that worked for me by using a combination of other answers and the Docs. (Took me a good day though)

    For anyone else who is struggling:

    Create a file called bundle-loader.js and add something like:

    module.exports = {
      importFiles: () => {
        const r = require.context()
         
        return 
      }
    }
    

    In your code import like:

    import bundleLoader from '/bundle-loader'
    

    Use like

    let  = bundleLoader.importFiles()
    

    In your test file right underneath other imports:

    jest.mock('../../utils/bundle-loader', () => ({
      importFiles: () => {
        return 
      }
    }))
    

提交回复
热议问题