Skip to content

Commit

Permalink
fix mocking nested required deps
Browse files Browse the repository at this point in the history
  • Loading branch information
ruyadorno committed Dec 17, 2020
1 parent 7f6245c commit 5980b7b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
4 changes: 3 additions & 1 deletion lib/mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ are the same used in ${filename} require calls`)
if (self.mocks.has(requiredFilePath))
return self.mocks.get(requiredFilePath)

return super.require(id)
const unmockedModule = new MockedModule(requiredFilePath, this)
unmockedModule.load(requiredFilePath)
return unmockedModule.exports
}
}

Expand Down
29 changes: 28 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1345,7 +1345,7 @@ t.test('require defining mocks', t => {
const i = t.mock('../index.js', {
'../lib/a.js': 'mocked-a',
})
t.equal(i(), 'mocked-a b a b d d', 'should get expected mocked result')
t.equal(i(), 'mocked-a b mocked-a b d d', 'should get expected mocked result')
t.end()
})
Expand Down Expand Up @@ -1461,5 +1461,32 @@ t.test('require defining mocks', t => {
)
})

t.test('should support mocking within nested deps', t => {
const f = t.testdir({
lib: {
'a.js':
`module.exports = require('./b.js')`,
'b.js':
`module.exports = require('./c.js')`,
'c.js':
`module.exports = () => 'c'`,
},
'test.js':
`const t = require('../..'); // tap
t.test('mocking deps of required modules', t => {
const a = t.mock('./lib/a.js', {
'./lib/c.js': () => 'mocked-c',
})
t.equal(a(), 'mocked-c', 'should get mocked-c result')
t.end()
})`,
})
return t.spawn(
process.execPath,
[ path.resolve(f, 'test.js') ],
{ cwd: f },
)
})

t.end()
})

0 comments on commit 5980b7b

Please sign in to comment.