Skip to content

Commit

Permalink
fix cicle required modules
Browse files Browse the repository at this point in the history
  • Loading branch information
ruyadorno committed Dec 17, 2020
1 parent 6b040a9 commit 8af0892
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ are the same used in ${filename} require calls`)
this.mocks.set(mockFilePath, mocks[key])
}

const seen = new Map()

class MockedModule extends Module {
require (id) {
const requiredFilePath = Module._resolveFilename(id, this)
Expand All @@ -45,7 +47,11 @@ are the same used in ${filename} require calls`)
if (!isRelative && !isAbsolute(id))
return super.require(id)

if (seen.has(requiredFilePath))
return seen.get(requiredFilePath).exports

const unmockedModule = new MockedModule(requiredFilePath, this)
seen.set(requiredFilePath, unmockedModule)
unmockedModule.load(requiredFilePath)
return unmockedModule.exports
}
Expand Down
29 changes: 29 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1488,5 +1488,34 @@ t.test('require defining mocks', t => {
)
})

t.test('should support cicle require', t => {
const f = t.testdir({
lib: {
'a.js':
`module.exports = require('./b.js')`,
'b.js':
`const c = require('./c.js')
const b = () => 'b and ' + c
b.extra = 'BBB'
module.exports = () => 'b and ' + c`,
'c.js':
`const b = require('./b.js')
module.exports = () => 'c and ' + b.extra`,
},
'test.js':
`const t = require('../..'); // tap
t.test('mocking cicled required deps', t => {
const a = t.mock('./lib/a.js', {})
t.ok('should not explode')
t.end()
})`,
})
return t.spawn(
process.execPath,
[ path.resolve(f, 'test.js') ],
{ cwd: f },
)
})

t.end()
})

0 comments on commit 8af0892

Please sign in to comment.