rewiremock
Simple es6-friendly mocking library inspired by the best libraries:
By its nature rewiremock has same behavior as Mockery. But it can have any behavior.
It covers any cases.
Rewiremock is an evolution of my way of explorations:
the better proxyquire,
the way ofresolveQuire,
and magic of proxyquire-webpack-alias.
Rewiremock was initially named as mockImports or mockModule. But was renamed for WireMock.
We shall not use that name, but rewire - is one of existing micking library.
Idealogy
- be simply
- be modular
- be secure
- be fast
Setup
First - define your mocks. You can do it in any place, this is just a setup.
import rewiremock from 'rewiremock';
...
rewiremock('fs')
.with({
readFile: yourFunction
});
rewiremock('path')
.by('path-mock');
rewiremock('reactComponent')
.withDefault(MockedComponent)
rewiremock('someLibrary')
.callThought()
.with({
onlyOneMethod
})
Running
Just enabled, and dont forget to disable.
beforeEach( () => rewiremock.enable() );
const someModule = require('someModule');
afterEach( () => rewiremock.disable() );
On enable rewiremock will wipe from cache all mocked modules, and all modules which requares them.
Including your test.
On disable it will repeat operation.
All test unrelated modules will be keept. Node modules, react, common files - everything.
As result - it will run faster.
Plugins
By default - rewiremock has limited features. You can extend it behavior by using plugins.
- nodejs. Common support to
usual
node.js application. Will absolutize all paths. - relative. Proxyquire-like behavior. Will overide only first level deps.
- webpack-alias. Enabled you to use webpack aliases as module names.
Nested declarations
Each time you require rewiremock - you will get brand new rewiremock.
You cannot declare mocks library
- it will erase itself.
But solution exists, and it is simply -
import rewiremock from 'rewiremock';
import rewiremock from 'rewiremock/nested';
See _test/nested.spec.js.
Isolation
Unit testing requires all decencies to be mocked. All!
To enable it, run
rewiremock.isolation();
rewiremock.withoutIsolation();
Then active - rewiremock will throw error on require of any unknown module.
Unknown is module which is nor mocked, nor marked as passthrough.
To enable few modules to in invisible
to rewiremock run
rewiremock.passBy();
rewiremock.passBy(/common/);
rewiremock.passBy(/React/);
rewiremock.passBy(/node_modules/);
rewiremock.passBy((name) => name.indexOf('.node')>=0 )
Thats all. Happy mocking!