From 32f6510c0b2550a6c693013a8fab41bd48eacfc0 Mon Sep 17 00:00:00 2001 From: Sondre Gjellestad Date: Wed, 3 Nov 2021 17:05:34 +0100 Subject: [PATCH] Fix for certain child modules not getting cleared (#20) --- fixture-empty.js | 3 +++ fixture-with-dependency.js | 2 ++ index.js | 4 ++-- test.js | 10 ++++++++++ 4 files changed, 17 insertions(+), 2 deletions(-) create mode 100644 fixture-empty.js diff --git a/fixture-empty.js b/fixture-empty.js new file mode 100644 index 0000000..8b46fbb --- /dev/null +++ b/fixture-empty.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = {}; diff --git a/fixture-with-dependency.js b/fixture-with-dependency.js index 436723d..5e9284f 100644 --- a/fixture-with-dependency.js +++ b/fixture-with-dependency.js @@ -1,5 +1,7 @@ 'use strict'; +// eslint-disable-next-line no-unused-vars +const _ = require('./fixture-empty'); const fixture = require('./fixture'); module.exports = () => fixture(); diff --git a/index.js b/index.js index b61e833..e28abdb 100644 --- a/index.js +++ b/index.js @@ -33,12 +33,12 @@ const clear = moduleId => { // Remove all descendants from cache as well if (require.cache[filePath]) { - const {children} = require.cache[filePath]; + const children = require.cache[filePath].children.map(child => child.id); // Delete module from cache delete require.cache[filePath]; - for (const {id} of children) { + for (const id of children) { clear(id); } } diff --git a/test.js b/test.js index 0cc2e26..840592d 100644 --- a/test.js +++ b/test.js @@ -36,6 +36,16 @@ test('clearModule() recursively', t => { t.is(require(id)(), 1); }); +test('clearModule() recursively, multiple imports', t => { + clearModule.all(); + const id = './fixture-with-dependency'; + t.is(require(id)(), 1); + t.is(require(id)(), 2); + t.is(require(id)(), 3); + clearModule(id); + t.is(require(id)(), 1); +}); + test('clearModule.single()', t => { clearModule.all(); const id = './fixture-with-dependency';