decache icon indicating copy to clipboard operation
decache copied to clipboard

Multiple instances of a module at different levels

Open stubar opened this issue 8 years ago • 3 comments

My app is structured like so

App
|-----clientConfig
|-----routes
          |-----controller
                    |-----------clientConfig

clientConfig is the troublesome module, it has some local vars, that aren't getting reset when I decache it in my tests. The are 2 unique instances of it, I know this by storing a local datestamp var when it's required. I think the problem maybe compounded by the fact I'm decaching the App module for each test.

I can fix the problem by deleting every single item from the cache, which seems a bit of a sledgehammer. I have come to a nicer solution where I delete the module in question and all it's ancestors stopping at the test itself. This seems to have gotten me out of my predicament, although I don't fully understand why.

This is the code I'm using..

var unrequire = (moduleName,deleteParents=false) =>{
        var fullPath = require.resolve(moduleName);
        var mod=require.cache[fullPath];
        if(mod) {
            if (mod.hasOwnProperty('parent') && deleteParents) {
                var parentId = mod.parent.id;
                var nextParentId;
                while (parentId && parentId !== __filename) {
                    if (require.cache[parentId] && require.cache[parentId].parent) {
                        nextParentId = require.cache[parentId].parent.id;
                    } else {
                        nextParentId = null;
                    }
                    if (require.cache[parentId]) {
                        delete require.cache[parentId];
                    }
                    parentId = nextParentId;

                }
            }
            delete require.cache[fullPath];
        }
        Object.keys(module.constructor._pathCache).forEach(function(cacheKey) {
            if (cacheKey.indexOf(moduleName)>0) {
                delete module.constructor._pathCache[cacheKey];
            }
        });
};

This maybe of use to your module or you maybe able to tell me where I'm going wrong in seeing such a strange occurrence.

stubar avatar Mar 22 '17 11:03 stubar

+1

andrsnn avatar Mar 31 '17 21:03 andrsnn

Pull Requests welcome. 👍

nelsonic avatar Mar 31 '17 22:03 nelsonic

Try with the latest version 4.3.0

4strid avatar Nov 03 '17 23:11 4strid