dwyl / dwyl/decache

Multiple instances of a module at different levels

Open
#28 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
153
Forks
12
PR merge metrics
No merged PRs in 30d

Description

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.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.