Skip to content

Commit

Permalink
Mock module a bit better (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
jdalton authored and iarna committed May 4, 2018
1 parent e51742a commit 64e77e6
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
9 changes: 8 additions & 1 deletion index.js
@@ -1,4 +1,5 @@
'use strict'
var Module = require('module')
var path = require('path')
var caller = require('caller')

Expand Down Expand Up @@ -59,14 +60,20 @@ function getCallerFilename () {

function installGlobally (toLoad, mocks) {
var callerFilename = getCallerFilename()
var parent = require.cache[toLoadPath] || null

// Inject all of our mocks
Object.keys(mocks).forEach(function (name) {
var namePath = resolve(callerFilename, name)
if (mocks[name] == null) {
delete require.cache[namePath]
} else {
require.cache[namePath] = {exports: mocks[name]}
var old = require.cache[namePath]
var mod = new Module(namePath, null)
mod.filename = namePath
mod.exports = mocks[name]
mod.parent = old ? old.parent : parent
require.cache[namePath] = mod
}
})

Expand Down
59 changes: 59 additions & 0 deletions test/injection-module.js
@@ -0,0 +1,59 @@
'use strict'
var path = require('path')
var test = require('tap').test
var Tacks = require('tacks')
var File = Tacks.File
var Dir = Tacks.Dir
var requireInject = require('../index')

var testdir = path.join(__dirname, path.basename(__filename, '.js'))
var adir = path.join(testdir, 'a')
var bdir = path.join(testdir, 'b')
var bfilename = bdir + '.js'

var fixture = new Tacks(
Dir({
'a.js': File(
"'use strict';\n" +
"require('./b');\n"
),
'b.js': File('')
})
)

test('setup', function (t) {
fixture.create(testdir)
t.end()
})

test('mock with details of original module', function (t) {
t.plan(3)

var bmod

Object.defineProperty(require.cache, bfilename, {
configurable: true,
enumerable: true,
get () {
return bmod
},
set (value) {
bmod = value
}
})

require(bdir)

requireInject(adir, {
[bdir]: 'mock'
})

t.equal(bmod.filename, bfilename)
t.equal(bmod.id, bfilename)
t.equal(bmod.parent, require.cache[__filename])
})

test('cleanup', function (t) {
fixture.remove(testdir)
t.end()
})

0 comments on commit 64e77e6

Please sign in to comment.