forked from testdouble/testdouble-jest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
43 lines (38 loc) · 1.32 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
* Usage:
* require('testdouble-jest')(td, jest)
*
* This will decorate td with `td.mock` to allow
* for module mocking using test double fakes instead
* of Jest's built-in ones
*/
module.exports = function (td, jest) {
ensureTdFeatures(td)
td.quibble.ignoreCallsFromThisFile()
function absolutify (moduleName) {
return td.quibble.absolutify(moduleName)
}
td.mock = function (moduleName, factory, options) {
var absoluteModulePath = absolutify(moduleName)
if (factory) return jest.mock(absoluteModulePath, factory, options)
const realThing = jest.requireActual(absoluteModulePath)
return jest.mock(absoluteModulePath, function () {
return td.imitate(realThing, moduleName + ': ' + nameFor(realThing))
}, options)
}
td.mock.requireMock = function (moduleName) {
return jest.requireMock(absolutify(moduleName))
}
td.mock.requireActual = function (moduleName) {
return jest.requireActual(absolutify(moduleName))
}
}
const ensureTdFeatures = function (td) {
if (!td.quibble || !td.imitate) {
throw new Error('testdouble-jest depends on td.imitate and td.quibble, added in [email protected] and [email protected], respectively.')
}
}
const nameFor = function (realThing) {
if (!(typeof realThing === 'function')) return ''
return realThing.name || '(anonymous function)'
}