mock-path-with-simple-spy
Mocks a given path with a simple spy that returns either a constant symbol or something provided by you.
Why?
Because in unit tests, we mock some dependency functions.
And, usually, we like them to return a constant value.
And, usually, we like to assert their calls/args.
And, usually, we require
the test subject multiple times.
This utility fits that pattern.
How?
Example
dep.js
// we will be mocking this file module x
index.js
// this module will be our test subject const dep = module + '-foo'
index.test.js
// unit tests here const assert = const mockPathWithSimpleSpy = const requireUncached = // set up a mockconst depMocks = // test Aconst depSpyA = depMocksnextvalue // mockconst subjectA = const actualA = assert // `./dep` is mockedassert // spy available // test Bconst depSpyB = depMocksnextvalueconst subjectB = const actualB = assert
API
mockPathWithSimpleSpy(path[, spyReturn])
(not a generator function)
path
The path to mock. Will be passed tomock
.spyReturn
(optional)
If provided, all spies return provided value.
If not provided, all spies share the same return value. A symbol withpath
as its description.
Returns an iterator, with the following properties:
next()
Onnext
, thepath
is mocked with a new simple-spy and the spy is returned.spyReturn
The spy’s return valuestop()
Callsmock.stop
on thepath
Caveats
module.parent
Uses So it must always be require
d
directly in the module where it is used.
This may be fixed by using
caller-path
instead of module.parent
,
so please report an issue
if you find that it bothers you.
require
s the mocked module
The path
is require
d
and the exported function’s length is examined,
for the purpose of the mock function
being of the same arity as the mocked function.