Giter Site home page Giter Site logo

thekashey / rewiremock Goto Github PK

View Code? Open in Web Editor NEW
482.0 5.0 31.0 2.62 MB

The right way to mock dependencies in Node.js or webpack environment.

License: MIT License

JavaScript 100.00%
mock proxyquire webpack dependency-injection nodejs mockery magic mock-library

rewiremock's Introduction

                     /$$      /$$ /$$                     /$$      /$$                     /$$      
                    | $$  /$ | $$|__/                    | $$$    /$$$                    | $$      
  /$$$$$$   /$$$$$$ | $$ /$$$| $$ /$$  /$$$$$$   /$$$$$$ | $$$$  /$$$$  /$$$$$$   /$$$$$$$| $$   /$$
 /$$__  $$ /$$__  $$| $$/$$ $$ $$| $$ /$$__  $$ /$$__  $$| $$ $$/$$ $$ /$$__  $$ /$$_____/| $$  /$$/
| $$  \__/| $$$$$$$$| $$$$_  $$$$| $$| $$  \__/| $$$$$$$$| $$  $$$| $$| $$  \ $$| $$      | $$$$$$/ 
| $$      | $$_____/| $$$/ \  $$$| $$| $$      | $$_____/| $$\  $ | $$| $$  | $$| $$      | $$_  $$ 
| $$      |  $$$$$$$| $$/   \  $$| $$| $$      |  $$$$$$$| $$ \/  | $$|  $$$$$$/|  $$$$$$$| $$ \  $$
|__/       \_______/|__/     \__/|__/|__/       \_______/|__/     |__/ \______/  \_______/|__/  \__/

Build Status coverage-badge version-badge Greenkeeper badge

Quick start

1. Install

  • yarn add --dev rewiremock or npm i --save-dev rewiremock

2. Setup

I would recommend not importing rewiremock directly from tests, but create a rewiremock.js file and require it - in this way, you can preconfigure rewiremock for all tests.

for ts/es6/esm use import

// rewiremock.es6.js
import rewiremock from 'rewiremock';
// settings
// ....
rewiremock.overrideEntryPoint(module); // this is important. This command is "transfering" this module parent to rewiremock
export { rewiremock }

for commonjs/nodejs use require('rewiremock/node')

// rewiremock.cjs.js
const rewiremock = require('rewiremock/node'); 
// nothng more than `plugins.node`, but it might change how filename resolution works
/// settings
rewiremock.overrideEntryPoint(module); // this is important
module.exports = rewiremock;

for webpack

// rewiremock.es6.js
import rewiremock from 'rewiremock/webpack';
/// settings
rewiremock.overrideEntryPoint(module); // this is important
export { rewiremock }

You will also need to add a few plugins to your webpack test configuration (no need to keep them all in production).

If you import rewiremock directly from your tests, you dont need overrideEntryPoint

3. Use

There are 3 ways to mock, all with pros and cons.

proxyquire - like

Simplest one.

 const file = rewiremock.proxy('file.js', {
   'dependency':  stub
 });
 // or
 const file = rewiremock.proxy(() => require('file.js'), {
    'dependency':  stub
  });

πŸ’‘to make it really "proxyquire like" - add .relative plugin. Which will allow mocking of direct dependencies only, like with proxyquire

import rewiremock, { addPlugin, plugins } from 'rewiremock';
addPlugin(plugins.relative);

mockery - like

Most powerfull one

 rewiremock('dependency').with(stub);
 rewiremock(() => require('dependency')).with(stub);
 rewiremock(() => import('dependency')).with(stub); // works with async API only
 rewiremock.enable(); 
 const file = require('file.js');
 rewiremock.disable();

jest - like

Shortest one

 // just place it next to `imports` and add a rewiremock/babel plugin 
 rewiremock('dependency').with(stub); 

πŸ’‘ requires rewiremock/babel plugin

4. Tune

There are plenty of plugins to make your life easier. For example - this is my favorite setup

import { resolve } from 'path';
import rewiremock, { addPlugin, overrideEntryPoint, plugins } from 'rewiremock';
import { configure } from 'rewiremock/lib/plugins/webpack-alias'; // actually dont use it

configure(resolve(`${__dirname}/../../webpack.config.test.js`));

overrideEntryPoint(module);
// we need webpack aliases
addPlugin(plugins.webpackAlias);
// and all stub names would be a relative
addPlugin(plugins.relative);
// and all stubs should be used. Lets make it default!
addPlugin(plugins.usedByDefault);

export { rewiremock };

What command to use???!!!

// use `require` instead of just the filename to maintain type information
const mock = rewiremock.proxy(() => require('somemodule'), r => {
   'dep1': { name: 'override' },
   // use all power of rewiremock to mock something as you want...
   'dep2': r.with({name: 'override' }).toBeUsed().directChildOnly(), // use all `mocking API`
}));

There are two important things here:

  • You can use require or import to specify the file to require and the file to mock. This helps to resolve file names and maintain type information(if you have it). See Guided Mocking below.
  • You can mix simplified helpers (like .proxy) and the main API.

ESM modules

If you want to support ESM modules(powered by @std/ESM, not native modules) you have to use the import function.

  • use .module - an "async" version of .proxy
const mock = await rewiremock.module(() => import('somemodule'), {...});
  • or just use import - that would
rewiremock(() => require('xxx').with({});
rewiremock('yyy').with({});

const file = await import('somemodule');

Ok! Let's move forward!

API

main API

  • rewiremock.enable() - wipes cache and enables interceptor.
  • rewiremock.disable() - wipes cache and disables interceptor.
  • rewiremock.around(loader, creator):Promise< T > - loads a module in an asynchronous sandbox.
  • rewiremock.proxy(file, stubs):T - proxyquire like mocking api, where file is file name, and stubs are an object or a function.
  • rewiremock.module(loader, stubs):Promise< T > - async version of proxy, where loader is a function.

mocking API

  • rewiremock(moduleName: string) - fabric for a moduleNames's mock
  • rewiremock(moduleImport: loader) - async fabric for a module import function.
    • .enable/disable() - to enable or disable mock (enabled by default).
    • .with(stubs: function | Object) - overloads module with a value
    • .withDefault(stub: function | Object) - overload default es6 export
    • .es6() - marks module as ES6( __esModule )
    • .by(otherModule: string| function) - overload by another module(if string provider) or by result of a function call.
    • .callThrough() - first load the original module, and next extend it by provided stub.
    • .mockThrough([stubFactory]) - first load the original module, and then replaces all exports by stubs.
    • .dynamic() - enables hot mock updates.
    • .toBeUsed() - enables usage checking.
    • .directChildOnly - will do mock only direct dependencies.
    • .calledFromMock - will do mock only dependencies of mocked dependencies.
  • rewiremock.getMock(moduleName: string|loader) - returns existing mock (rewiremock(moduleName) will override)

isolation API

  • rewiremock.isolation() - enables isolation
  • rewiremock.withoutIsolation() - disables isolation
  • rewiremock.passBy(pattern or function) - enables some modules to pass throught isolation.

sandboxing

  • rewiremock.inScope(callback) - place synchronous callback inside a sandbox.

helper functions

  • rewiremock.stubFactory(factory) - define a stub factory for mockThrough command.

Automocking

Rewiremock supports (inspired by Jest) auto __mocks__ing.

Just create __mocks__/fileName.js, and fileName.js will be replaced by the mock. Please refer to Jest documentation for use cases.

If you don't want a particular file to be replaced by its mock - you can disable it with:

 rewiremock('fileName.js').disable();

Which API to use?

Yep - there are 4 top-level ways to activate a mock - inScope, around, proxy or just enable.

A common way to mock.

Rewiremock provides lots of APIs to help you set up mocks, and get the mocked module.

  • If everything is simple - use rewiremock.proxy. (~proxyquire)
  • If you have issues with name resolve - use rewiremock.module and resolve names by yourself.
  • If you need scope isolation - use rewiremock.around, or inScope.
  • If you need advanced syntax and type checking - use rewiremock.around.
  • You always can just use .enable/.disable (~ mockery).

All the mocks await you to provide "stubs" to override the real implementation. If you want just to ensure you have called endpoints – use rewiremock('someFile').mockThrough.

Usage

  • proxy will load a file by its own ( keep in mind - name resolution is a complex thing)
const mock = rewiremock.proxy('somemodule', (r) => ({
   'dep1': { name: 'override' },
   'dep2': r.with({name: 'override' }).toBeUsed().directChildOnly(), // use all `mocking API`
   'dep3': r.mockThrough() // automatically create a test double  
}));
  • you can require a file by yourself. ( yep, proxy is a "god" function)
const mock = rewiremock.proxy(() => require('somemodule'), {
   'dep1': { name: 'override' },
   'dep2': { onlyDump: 'stubs' }  
}));
  • or use es6 import (not for Node.js mjs real es6 modules) module is an async version of proxy, so you can use imports
const mock = await rewiremock.module(() => import('somemodule'), {
   'dep1': { name: 'override' },
   'dep2': { onlyDump: 'stubs' }  
}));
  • around - another version of .module, where you can do just anything.
const mock = await rewiremock.around(() => import('somemodule'), () => {
   rewiremock('dep1').with('something');  
   callMom();
   // prepare mocking behavior
}));
  • enable/disable - Low level API
  rewiremock('someThing').with('someThingElse')
  rewiremock.enable();
  // require something
  rewiremock.disable();

In all the cases you can specify what exactly you want to mock, or just mock anything

   addPlugin(plugins.mockThroughByDefault);  

Hoisted mocking

You can also use a top-level mocking, the same as Jest could only provide

import sinon from 'sinon';
import rewiremock from 'rewiremock';
import Component1 from 'common/Component1';
import selectors from 'common/selectors';

rewiremock('common/Component1').by('common/Component2');
rewiremock('common/Component2/action').with({ action: () => {} });
rewiremock('common/selectors').mockThrough(() => sinon.stub());

selectors.findUser.returns("cat"); // this is sinon stub.

As result Component1 will be replaced by Component2, action with empty function and all selectors by sinon stubs, with one configured.

This is only possible via babel plugin, and without it, this code will be executed without any sense, as long mocking will be configured after the files required.

Limitations

  • Other babel plugins, including JSX, won't work inside webpack hoisted code. But you may define any specific code in "functions", and let JavaScript hoist it.
  • Most variables, that you have defined in the file, are not visible to hoisted code, as long they are not yet defined. Only functions will be hoisted.
  1. Add rewiremock/babel into the plugin section of your .babelrc or babel.config.js file
// .babelrc
{
  "presets": [
    //.....
  ],
  "plugins": [
    "rewiremock/babel"
  ]
}
  1. This example will be transpiled into
import sinon from 'sinon';
import rewiremock from 'rewiremock';

rewiremock('common/Component1').by('common/Component2');
rewiremock('common/Component2/action').with({ action: () => {} });
rewiremock('common/selectors').mockThrough(() => sinon.stub());

rewiremock.enabled();

import Component1 from 'common/Component1';
import selectors from 'common/selectors';

rewiremock.disable();

selectors.findUser.returns("cat"); // this is sinon stub.

Keep in mind - rewiremock will hoist mock definition next to rewiremock import.

  • You can use anything above rewiremock import
  • You can mock anything below rewiremock import

Changing the mocks after the mocking

It is possible to partially change mocking already being applied.

 rewiremock('./foo')
  .callThrough()
  .with({ action1: action1Stub1 })
  .dynamic();

 const foo = require('./foo');
 foo.action == action1Stub1;
 
 rewiremock.getMock('./foo')
   .with({ action1: action1Stub2 });
 
 //while will RESET the mock, and could not change existing ones.
 rewiremock('./foo')
    .with({ action1: action1Stub2 });
 
 foo.action == action1Stub2;
 
 rewiremock('./foo')
    .with({ });
 
 foo.action == theRealFoo;

Changing the hoisted mocks

 import rewiremock from 'rewiremock';
 import foo from './foo';
 
 rewiremock('./foo') 
   .with({ action1: action1Stub1 })
   .dynamic();

 const fooMock = rewiremock.getMock('./foo');
 
 describe(..., () => {
   it('...', () => {
     fooMock.with({ });
     
     // while may NOT found the mock
     rewiremock.getMock('./foo').with({ });
   });
 })

Guided mocking

You may use require or import to let IDE help you to properly write fileName, and hide all filename resolution and transformation behind the scenes. But there are things you have to keep in mind

  1. Resolution of synchronous API happens on .enable
rewiremock(() => require('./fileToMock1')); // this mock would work
rewiremock.enable();
rewiremock(() => require('./fileToMock2')); //this mock WOULD NOT WORK!
  1. Using async API will throw an error
rewiremock(() => import('./fileToMock1'));  
rewiremock.enable(); // this is an exception
  1. Async API requires async API
rewiremock.module( () => import('file')) // this is ok
rewiremock.around(..., rw => rw.mock(() => import('file2'))) // this is ok

Type safety

Rewiremock can provide type-safe mocks. To enable type-safety to follow these steps:

  1. Use TypeScript or Flow.
  2. Use dynamic import syntax.
  3. Use rewiremock.around or rewiremock.module to perform a mock.
  4. Use the async form of rewiremock mock declaration.
// @flow

import rewiremock  from 'rewiremock';

rewiremock.around(
  () => import('./a.js'), 
  mock => {
  mock(() => import('./b.js'))
    .withDefault(() => "4")
    .with({testB: () => 10})
    .nonStrict() // turn off type system
    .with({ absolutely: "anything" })
  }
);

If default export is not exists on module 'b', or there is no named export testB, or types do not match - type system will throw.

If you will declare an async mock, it will not be resolved by the time of execution - Rewiremock will throw on Error.

If you have async imports inside a mocked file, follow this syntax

rewiremock.around(
  () => import('./a.js'), 
  mock => {
  // just before loader function rewiremock enabled itself
  mock(() => import('./b.js').then(mock=>mock)) // mocks `live` one `tick` more
  // just after loader function resolved rewiremock disables itself
    mock => {
    ....
    }
  }
);

Type safety for JavaScript

Rewiremock can check mock against the real implementation. This does not perform type checking, but could check exported names and exported types (function vs number, for example).

Rewiremock expects that mock will be less or equal than the original file.

rewiremock: mocked export "somethingMissing" does not exist in ./b.js
rewiremock: exported type mismatch: ./b.js:default. Expected function, got number

To activate exports comparison

 rewiremock('somemoduname')
   .toMatchOrigin(); // to activate
   
// or
import rewiremock, { addPlugin, removePlugin, plugins } from 'rewiremock';
addPlugin(plugins.alwaysMatchOrigin);   

Setup

To run with Node.js

Just use it. You can also activate node.js, which will double-check all modules names on a real FS, but... everything might work out of the box.

PS: Just use usedByDefault to ensure module names are resolved correctly.

There is also a special entry point for node.js, with nodejs plugin activated, and rewiremock as es5 export

const rewiremock = require('rewiremock/node');

// meanwhile
const rewiremock = require('rewiremock').default;

To run inside webpack environment.

Rewiremock can emulate few webpack features(like aliases) in node.js environment, but it also can be run inside webpack.

Actually rewiremock is the first client-side mocking library

But not so fast, handy. First, you have to have 3(!) Plugins enabled.

  1. webpack.NamedModulesPlugin(). To enlight the real names of modules, not "numbers". Enabled by default in webpack "dev" mode
  2. webpack.HotModuleReplacementPlugin(). To provide some information about connections between modules. Might be (and usually) already enabled, double activation of this plugin might break everything.
  3. rewiremock.webpackPlugin. To add some magic and make gears rolling.
plugins: [
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new (require("rewiremock/webpack/plugin"))()
]

That's all. Now all magic will happen at the client-side.

It is better to use .proxy/module command with direct require/import and leaves all names conversion to webpack.

Hint

For better dev experience include special configuration of webpack

import rewiremock from 'rewiremock/webpack';

webpack troubleshooting

Currently, there are 2 known problems, both for mocha+webpack, ie using node.js to run webpack bundle:

  • TypeError: Cannot read property 'webpackHotUpdate' of undefined

    Caused by babel. Just don't use babel then running webpack bundles (ie babel-register). Use babel to create bundles.

  • TypeError: Cannot read property 'call' of undefined

    Caused by webpack. Sometimes it does not include some important files. To solve this problem just import('rewiremock/webpack/interceptor') in scaffolding. The problem is simply - this file does not exist in the bundle.

To actually... mock

First - define your mocks. You can do it in any place, this is just a setup.

 import rewiremock from 'rewiremock';
 ...
 
 // totaly mock `fs` with your stub 
 rewiremock('fs')
    .with({
        readFile: yourFunction
    });
  
 // replace path, by other module 
 rewiremock('path')
    .by('path-mock');
 
 // replace enzyme by preconfigured one  (from https://medium.com/airbnb-engineering/unlocking-test-performance-migrating-from-mocha-to-jest-2796c508ec50)
  rewiremock('enzyme')
     .by(({requireActual}) => {
    // see rest of possible params in d.ts file
         const enzyme = requireActual('enzyme');         
         if (!mockSetup) {
           const chai = requireActual('chai');
           const chaiEnzyme = requireActual('chai-enzyme');
           chai.use(chaiEnzyme());           
         }
         return enzyme;
     });
  
 // replace default export of ES6 module 
 rewiremock('reactComponent')
    .withDefault(MockedComponent)
     
 // replace only part of some library and keep the rest 
 rewiremock('someLibrary')
    .callThrough() 
    .with({
        onlyOneMethod
    })
    
 // secure yourself and from 'unexpected' mocks
 rewiremock('myDep')
     .with(mockedDep) 
     .calledFromMock()

Running

There is a simply way to do it: Just enable it, and dont forget to disable it later.

 //in mocha tests
 beforeEach( () => rewiremock.enable() );
 //...
 // here you will get some advantage in type casting and autocompleting.
 // it will actually works...
 const someModule = require('someModule'); 
 //...
 afterEach( () => rewiremock.disable() );

Once enabled, rewiremock will wipe all mocked modules from cache, and all modules which require them.

Including your test.

Once disabled it will restore everything.

All unrelated to test dependencies will be kept. Node modules, react, common files - everything.

As a result - it will run faster.

inScope

Sometimes you will have independent tests in a single file, and you might need separate mocks for each one. inScope execute callback inside a sandbox, and all mocks or plugins or anything else you have added will not leaks away.

 rewiremock.inScope( () => {
   rewiremock('something').with(something);
   rewiremock.enable();
   // is 'something' mocked? Yes
   ....
   rewiremock.disable();
   // is 'something' mocked? No
   // is it still listed as mock? Yes
 }); 
 // is 'something' mocked or listed? No

Around

And there is a bit harder way to do it - scope. inScope will create a new internal scope, next you can add something new to it, and then it will be destroyed. It will also enable/disable rewiremock just in time.

This helps keep tests in isolation.

PS: scopes are nesting each other as javascript prototypes do.

rewiremock.around(
    () => import('somemodule'), // load a module. Using import or require.
    // just before it you can specify mocks or anything else
    (mock) => { 
        addPlugin(nodePlugin);

        mock('./lib/a/foo').with(() => 'aa');
        mock('./lib/a/../b/bar').with(() => 'bb');
        mock('./lib/a/../b/baz').with(() => 'cc');
    }
) // at this point scope is dead
    .then((mockedBaz) => { 
        expect(mockedBaz()).to.be.equal('aabbcc');
    });

or just

rewiremock.around(() => import('somemodule')).then(mockedModule => doSomething)  

or

rewiremock.around(
    () => import('somemodule').then( mockedModule => doSomething),    
    (mock) => aPromise   
);

Currently, .inScope is the only API capable to handle es6(not node [m]js!) dynamic imports.

Proxy

Sometimes it is much easier to combine all the things.

// preferred way - create stubs using a function, where R is mock creator
rewiremock.proxy('somemodule', (r) => ({
   'dep1': { name: 'override' },
   'dep2': r.with({name: 'override' }).toBeUsed().directChildOnly() // same powerfull syntax
}));

// straight way - just provide stubs.
rewiremock.proxy('somemodule', {
   'dep1': { name: 'override' },
   'dep2': { name: 'override' }
 }));

Plugins

By default - rewiremock has limited features. You can extend its behavior via plugins.

  • relative. A bit simplistic, proxyquire-like behavior. Will override only first level dependencies, and will wipe a lot of modules from a cache. If you need override at other place - use .atAnyPlace modificator.
  • nodejs. Common support to "usual" Node.js application. Will absolutize all paths. Will wipe cache very accurately.
  • webpack-alias. deprecated. Enables you to use webpack aliases as module names. Please use node-js resolution for this.
  • childOnly. Only first level dependencies will be mocked.
  • protectNodeModules. Ensures that any module from node_modules will not be wiped from a cache.
  • toBeUsed. Adds feature. The only plugin enabled by default.
  • disabledByDefault. All mocks will be disabled on create and at the end of each cycle.
  • mockThroughByDefault. All mocks mocked through.
  • usedByDefault. All mocks to be used by the fact (reverse isolation)
import rewiremock, { addPlugin, removePlugin, plugins } from 'rewiremock';     

addPlugin(plugins.webpackAlias);
removePlugin(plugins.webpackAlias);

Nested declarations

If you import rewiremock from another place, for example, to add some defaults mocks - it will not gonna work. Each instance of rewiremock in independent. You have to pass your instance of rewiremock to build a library. PS: note, rewiremock did have nested API, but it was removed.

Isolation

Unit testing requires all dependencies to be mocked. All! To enable it, run

 rewiremock.isolation();
 //or
 rewiremock.withoutIsolation();

Then active - rewiremock will throw error on require of any unknown module.

The unknown is a module which is nor mocked, nor marked as pass-through.

To make few modules to be invisible to rewiremock, run

rewiremock.passBy(/*pattern or function*/);

rewiremock.passBy(/common/);
rewiremock.passBy(/React/);
rewiremock.passBy(/node_modules/);
rewiremock.passBy((name) => name.indexOf('.node')>=0 )

Reverse isolation

Sometimes you have to be sure, that you mock was called. Isolation will protect you then you add new dependencies, .toBeUsed protect you from removal.

Jest

Jest is a very popular testing framework, but it has one issue - is already contain mocking support.

Do not use rewiremock and jest. Even if it is possible.

Jest will not allow ANY other mocking library to coexists with Jest

To use rewiremock with Jest add to the beginning of your file

// better to disable auto mock
jest.disableAutomock();

// Jest breaks the rules, and you have to restore nesting of modules.
rewiremock.overrideEntryPoint(module);

// There is no way to use overload by Jest require or requireActual.
// use the version provided by rewiremock. 
require = rewiremock.requireActual;

!!! the last line here may disable Jest sandboxing. !!!

Also, it will disable Jest transformation, killing all the jest magics.

To be able to continue using ES6/imports - you have to enforce Babel to be applied in the common way.

describe('block of tests', () => {
  // require babel-register in describe or it block.
  // NOT! On top level. Jest sandboxing and isolation are still in action,
  // and will reset all settings to default
  require("babel-register");
})

PS: Jest will set BABEL_ENV to test.

It is better just to use rewiremock.requireActual, without overriding global require.

Your own setup.

In most cases you have to:

  • add plugin
  • setup default passBy rules
  • add some common mocks
  • do something else.

And it is not a good idea to do it in every test you have.

It is better to have one setup file, which will do everything for you

  • Part 1 - man in the middle
  // this is your test file
  
  // instead of importing original file - import your own one
  // import rewiremock from 'rewiremock';
  import rewiremock from 'test/rewiremock';    
  • Part 2 - create your own one
    // this tests/rewiremock.js
    
    import rewiremock, { addPlugin, overrideEntryPoint} from 'rewiremock';
    // do anything you need
    addPlugin(something);
    rewiremock('somemodule').with(/*....*/);   
    
    // but don't forget to add some magic
    overrideEntryPoint(module); // <-- set yourself as top module
    // PS: rewiremock will wipe this module from cache to keep magic alive.
       
    export default rewiremock;
  • Part 3 - enjoy. You extract some common code into a helper. And things become a lot easier.

Default configuration

Absolutely the same - preconfiguring rewiremock one can achieve via default configuration.

Just put rewiremock.config.js in the root dir, next to project.json, and export a configuration function

// rewiremock.config.js
import wrongrewiremock, {plugins} from 'rewiremock';

export default rewiremock => {
  // do everything with "right" rewiremock
  rewiremock.addPlugin(plugins.nodejs)
}

Caching

Default cache policy follows these steps:

  1. Preparation:
  • all files required from the original test, while interceptor is active, will bypass cache.
  • all files you indicate as mocks will be removed from the cache.
  • all "soiled" files which rely on mocks - will also be removed from the cache.
  • repeat.
  1. Finalization
  • repeat all mocks and possible "soiled" by mocks files.
  • copy over the old cache.
  • or restore the old cache completely if forceCacheClear mode is set.

The last variant is the default for proxyquire and mockery, also it is more "secure" from different side effects. Regardless, default is the first variant - as a way faster, and secure enough.

As a result of this mocking strategy, you can mock any file at any level, while keeping other files cached.

Hint

If you don't want this - just add relative plugin. It will allow mocking only for modules

required from module with parent equals entryPoint.

PS: module with parent equals entryPoint - any module you require from the test (it is an entry point). required from that module - the first level required. Simple.

Own plugins

Don't forget - you can write your own plugins. plugin is an object with fields:

{
// to transform name. Used by alias or node.js module
fileNameTransformer: (fileName, parentModule) => fileName;
// check should you wipe module or not. Never used :)
wipeCheck: (stubs, moduleName) => boolean,
// check is mocking allowed for a module. User in relative plugin
shouldMock: (mock, requestFilename, parentModule, entryPoint) => boolean
}

Extensions

Rewiremock will automatically try to resolve file

  • by specified name
  • adding .js, .jsx, .ts, .tsx, .mjs
  • you can override defaults
import {resolveExtensions} from 'rewiremock';
resolveExtensions(['.wasm', '.mjs', '.js', '.json']);

resolveExtensions is quite similar to webpack's resolve extensions.

Not working?

If something is not working - just check that you:

  • added a plugin to transform names (Node.js, webpackAlias or relative)
  • use .toBeUsed for each mocks And they were mocked. If not - rewiremock will throw an Error.

Goal

  • give the ability to mock everything - CommonJS, ES6, inside Node.js or webpack.
  • give the ability to do correctly - isolation, type checking, powerful API
  • give the ability to do it easy - simple API to cover all the cases.

Other libraries

Dependency mocking, inspired by the best libraries:

  • mockery - rewiremock is a better mockery, with the same interface.
  • proxyquire - rewiremock is a better proxyquire, with the same interface.
  • mock-require - things must not be complex, rewiremock is not.
  • jest.mocks - jest is awesome. As well as rewiremock.

Rewiremock is a better version of your favorite mocking library. It can be used with mocha, ava, karma, and anything that's not jest.

By design, rewiremock has the same behavior as Mockery. But it can behave like other libraries too, exposing handy interfaces to make mocking a joy. Supports type-safe mocking and provides TS/Flow types for itself.

Wanna read something about?

Rewiremock - medium article all by tag

Licence

MIT

Happy mocking!

rewiremock's People

Contributors

boneskull avatar dapplion avatar dogoku avatar fabioatcorreia avatar greenkeeper[bot] avatar happykmm avatar kumamon2017 avatar langri-sha avatar ljqx avatar lmammino avatar maandagdev avatar onlywei avatar patrickshaw avatar regnarock avatar thekashey avatar theolampert avatar verkholantsev avatar xesenix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

rewiremock's Issues

How to mock promisified call to s3 with Typescript?

Consider the following file index.ts:

import { S3 } from 'aws-sdk'
import { promisify } from 'util'

const s3 = new S3({ apiVersion: '2006-03-01' })
const getObject = promisify<S3.GetObjectRequest, S3.GetObjectOutput>(
  () => s3.getObject // tslint:disable-line: no-unbound-method
)

/**
* Describes a s3 object.
*/
export interface IS3ObjectInfo {
  bucketArn: string
  objectKey: string
}

/**
* Fetches an object from an s3 bucket.
*/
export const fetchObjectFromS3 = async (
  objectInfo: IS3ObjectInfo
): Promise<Buffer> => {
  const { bucketArn, objectKey } = objectInfo

  const file = await getObject({
    Bucket: bucketArn,
    Key: objectKey
  })

  if (!Buffer.isBuffer(file.Body)) {
    throw new Error('file body is not a buffer')
  }

  return file.Body
}

My objective is to mock the promisified createObject call. What I tried:

// tslint:disable: no-implicit-dependencies no-magic-numbers no-console
// tslint:disable: no-var-requires no-require-imports comment-format
// tslint:disable: only-arrow-functions

import { fetchObjectFromS3 } from '../src'
import rewiremock from 'rewiremock'

describe('serverless-diy-bucket', function(): void {
  this.timeout('30s')

  it.only('should fetch an object from s3 with from object info', async () => {
    rewiremock('aws-sdk/S3').with({
      getObject: (): void => {
        console.log('get object was called')
      }
    })

    rewiremock.enable()

    const file = await fetchObjectFromS3({
      bucketArn: 'arn:aws:s3:::myarn',
      objectKey: 'alpha/a-company/input/test.txt'
    })

    console.log(file)

    rewiremock.disable()
  })
})

This doesn't log to the console. I suspect that the reference to aws-sdk/S3 might be invalid, or that at this point it is too late to intercept the library?

Trying to mock in Meteor without success.

Hi again @theKashey,

I am trying to use rewiremock with the Meteor JS framework without much success.

I imagine you wont be able to offer any help in this regard but I though I'd try :)

I've created a small reproduction of my issue in this repo.

Meteor uses Babel under the hood to transpile import statements into require statements however there must be something else going on under the hood as my test is still failling.

You should be able to see this when running the npm test command after installing Meteor. As you can see we have our own test runner in order to load Meteor globals among others but it is still mocha.

No matter the outcome, thanks for your help.

An in-range update of wipe-node-cache is breaking the build 🚨

The dependency wipe-node-cache was updated from 2.0.0 to 2.1.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

wipe-node-cache is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • βœ… ci/circleci: Your tests passed on CircleCI! (Details).
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 2 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Question: How to mock dependency’s dependency?

Given this setup;

/client.js

const client = () => { /* ... */ };
module.exports = client;

/router.js

const client = require('./client');
const router = () => { /* ... */ };
module.exports = router;

/server.js

const router = require('./router');
const createServer =  () => { /* ... */ };
module.exports = { createServer };

/server.test.js

const mock = require('rewiremock').default;
const clientSpy = jasmine.createSpy('clientSpy');
const router = mock.proxy('./router', { './client': clientSpy });
const { createServer } = mock.proxy('./server', { './router': router });
// Tests
describe('server', () => { /* ... */ });

....is there a way to mock the export of client.js from server.test.js thru router.js?

Unable to import rewiremock into .jsx file

Thanks for this tool, it has been wonderful for node tests.

I'm using webpack 4 with Karma, and I am having an issue when using rewiremock while testing .jsx files. Would this be an issue with rewiremock, or something in my karma config? I have not had issues with any other imports.

import rewiremock from 'rewiremock/webpack';

// Error:
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR   
  SyntaxError: Unexpected token 'const'

When not using the webpack module (mport rewiremock from 'rewiremock';) I get this:

PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
  SyntaxError: Expected an identifier but found '{' instead

What other information would you need from me?

Thanks,
-Dave

difficulty using rewiremock.proxy with local file

Hi guys,

I'm having troubles trying to inject dependencies into a tested module within create-react-app environment.

my test configuration looks like this:

beforeEach(() => {
        [...]

        // this works well:
        StaggeredMotion = rewiremock.proxy('react-motion/lib/StaggeredMotion', {
            raf: mockRaf.raf,
            'performance-now': mockRaf.now,
        });

        // this fails: see error below
        MyComponent = rewiremock.proxy('../mycomponent', {
            'react-motion': {
                StaggeredMotion: StaggeredMotion,
            },
        }).default;
});

Here's the error I get:

/[...]/mycomponent.js:13
    import './mycompoent.css';
           ^^^^^^^^^^^^^^^^^^^^^^

    SyntaxError: Unexpected string

      at Function.mockLoader [as _load] (node_modules/rewiremock/lib/executor.js:325:37)
      at requireModule (node_modules/rewiremock/lib/executor.js:75:47)

actually every import statement will fail with "Unexpected string" or "Unexpected token" at this point.

If I use:

        // this has no effect
        MyComponent = rewiremock.proxy(() => require('../mycomponent'), {
            'react-motion': {
                StaggeredMotion: StaggeredMotion,
            },
        }).default;

This does not fail but it has simply no effect (nothing is changed).
As a workaround I manually inject my mock 'StaggeredMotion' as I have control over the code of 'mycomponent' but this is not ideal.
am I missing something ?
Thanks !

Jest: Setup problems

Hi, could you please tell me if I'm doing something wrong with setup.
I tried to follow your specs but I don't see any results at the moment.
What I'm trying to do is to mock external dependency intl-locales-supported so that it returns
custom result instead of real one. But rewiremock('intl-locales-supported')... and rewiremock.enable(); do nothing. It doesn't work if I even try to mock main file itself rewiremock('../core')... . Maybe I missed something important in configuration. I'm running tests using jest.
Thanks in advance.

// i18n.spec.js
...
import rewiremock from 'rewiremock';
...
beforeAll(() => {
  rewiremock('intl-locales-supported')
	.with(() => {
	  return '------test-------';
	});

  rewiremock.enable();
  const mockedCore = require('../core');
  mockedCore.localeLoaders.en();
});
afterAll(() => {
  rewiremock.disable();
});
.	
...

// core.js
...
import isIntlLocaleSupported from 'intl-locales-supported';

export const localeLoaders = {
  en: async () => {
    // TODO remove
    console.info(isIntlLocaleSupported('en'));
    if (global.Intl && isIntlLocaleSupported('en')) {
...


// .babelrc
...
"test": {
      "plugins": [
        "transform-promise-to-bluebird",
        "transform-decorators-legacy",
        "dynamic-import-node"
      ]
    }
...

An in-range update of webpack-cli is breaking the build 🚨

The devDependency webpack-cli was updated from 3.1.1 to 3.1.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

webpack-cli is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • βœ… ci/circleci: Your tests passed on CircleCI! (Details).
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 17 commits.

  • 795ac48 v0.1.2
  • 8225339 chore: v.3.1.2>
  • fb6945b Merge pull request #618 from webpack/fix/watch-info
  • 99f5a69 Merge pull request #616 from rishabh3112/patch-4
  • 4cba51d Merge pull request #615 from rishabh3112/patch-3
  • d4e1614 fix: replace test regex
  • f3a225a docs(readme): update webpack-cli to webpack CLI
  • 9aed0dc fix(tapable): fix hook options
  • dc4ded9 docs(init): update headers
  • 747aef9 docs(readme): change addons to scaffolds
  • f8187f1 docs(readme): update links
  • 2ccf9a9 docs(init): update init documentation
  • 3844671 docs(readme): update README.md (#614)
  • da05c2f docs(readme): update Readme based on feedback
  • 93ebcc2 chore(docs): update readme

There are 17 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

TS2536: Type '"default"' cannot be used to index type 'Ts'. After upgrading to TS 3.1.1

I just tried upgrading my TypeScript app from TS 3.0.1 to 3.1.1. When compiling it with webpack, having rewiremock as one of our (dev-)dependencies, compilation breaks at this point:

    ERROR in [at-loader] ./node_modules/rewiremock/rewiremock.d.ts:122:66 
        TS2536: Type '"default"' cannot be used to index type 'Ts'.

Interestingly, when I compile with tsc, I do not get this error.

Mocking with supertest in Node, not working?

Hey there, brand new to your library. I am using supertest to test my Express routes, and one of my route files uses the firebase admin sdk.

I want to mock the firebase admin sdk, so as a first test to confirm that rewiremock is working, I have assigned an empty object as the dependency for firebase. I proxy the module that handles my routes '../api/controlelrs/auth', and this is the module that directly imports the 'firebase-admin' module from the firebase sdk:

it('Verifies token and returns 200', done => {
      const rewiremock = require('rewiremock/node').default
      const mock = rewiremock.proxy('../api/controllers/auth', {
        'firebase-admin': new function (location) {
          return {}
        }()
      }).default

     request(app)
              .post(API_URL)
              .send({ phone: PHONE, token })
              .end((err, res) => {
                if (err) return done(err)
                expect(res.statusCode).to.be.equal(200)
                done()
              })
    })

What happens here is that verifyIdtoken from the REAL firebase admin sdk is called within my route. I verified by adding a console.log inside of the real firebase-admin library.

What I expected to happen was for my test console.log to not be called, as I'm hoping that the rewiremock library will replace the real firebase SDK with a mock (in the case of this example, an empty object).

Like I said, I'm new to using your library, maybe I am not setting up something correctly. Can you help? Thank you!

Danny

Support for mocking ES6 classes?

class Foo {
};
export default Foo; // not the default itself should be mocked but its instances

As I understand rewiremock works only with functions, i.e. I couldn't figure out how to mock classes. @theKashey Would you please provide some clues whether it's possible or not?

Thank you!

Supporting non-modern (ES5) browsers

Though rewiremock itself is built into ES5 & ES6, the rewiremock/webpack/interceptor is still ES6 only. Which limits it's usage in non-modern browsers like IE11.

Better to make rewiremock/webpack/interceptor ES5 compatible to ease the adoption. It would be an easy change. If it's ok I can make the change and add lint for it to prevent future break.

question: nodejs plugin and esm

Hi,

I was having some trouble using the nodejs plugin and relative paths with esm and rewiremock.module(). I'm unable to provide a minimal case to reproduce the problem I'm having, but I'll try to explain:

  • lib/foo.js is a module
  • lib/baz.js is another module
  • lib/bar/quux.js is yet another module
  • lib/bar/quux.js depends on lib/foo.js
  • lib/foo.js depends on lib/baz.js
  • test/bar/quux.spec.js is a test for lib/bar/quux.js, which uses rewiremock to stub lib/foo.js
  • test/foo.spec.js is a test for lib/foo.js, which uses rewiremock to stub lib/baz.js

This is how I'm using rewiremock:

  • stubs uses module paths relative to the test files
  • I'm using overrideEntryPoint() in a separate test helper file to load rewiremock
  • I'm running my tests via mocha -r esm, and with the nodejs plugin enabled.
  • I'm using the rewiremock.module(() => import('/path/to/module') syntax.

If I run each of those two tests individually, they both pass. If I run them together, test/bar/quux.spec.js runs first, then test/foo.spec.js runs. The latter fails, as it can't find lib/baz.js, which is stubbed via the relative path ../lib/baz.

In the resulting stack trace, test/bar/quux.spec.js appears at the top. Running the debugger, when test/foo.spec.js is trying to stub ../lib/baz, the "parent" module is test/bar/quux.spec.js, which seems incorrect.

A couple things I've noticed:

  • If I disable the nodejs plugin and use paths relative to the files under test (e.g., lib/foo.js stubs ./baz instead of ../lib/baz), all tests pass together (in other words, I'm not blocking on a fix)
  • Using rewiremock.enable() paired with rewiremock.disable() seems to have no effect whatsoever

So my question is if I should be using the nodejs plugin, or a different plugin, and how can I specify relative-to-test-file module paths to be stubbed? Is there a bug here?

Thanks for your work on this module!

Using webpack context configuration property stops mocking from working

I may be configuring something incorrectly, but I've found when using the context configuration property in a webpack config, mocking fails.

I created a simpler repository to check this here: https://github.com/bameyrick/rewiremock-test

In the master branch I have a version where I'm not using the context property in the webpack config. If I run yarn test the mocking works correctly.

However in the using-context branch where I've added a context property in the webpack config, a basePath in the karma config and updated the path to mock fetch.js in index.spec.js, it seems that rewiremock finds fetch.js for mocking but does not replace it with fetch.stub.spec.js.

I tried console.log(__webpack_modules__) in the using-context branch and could see ./js/fetch.js in there, and rewiremock doesn't complain that it can't find it, but it doesn't seem to mock the fetch function.

wipeCache is slow on large projects

Thousand of files could greatly slowdown wiping cache before and after mocking. It is just a few milliseconds, and they form seconds...

The problem is simple - wipe-node-cache goes thought all cache entities and asks "should I wipe it", next rewiremock checks it, at least 3 times - does mock exists, that plugins think, what if filename is incomplete.

Few simple checks per thousands of files.
The goal is simple - you can mock something anywhere, and rewiremock will wipe anything "between" that file and entry point.

The fix:

  • mocks with absolute paths should be wiped directly - O(1) lookup

  • mocks with relative paths could operate on inverse index (I mean reverse string order) - O(1) lookup

  • proxy/around should support auto naming resolution.

  • thus - shouldMock shall not be able to mock something, only to prevent something from mocking. Actually, as it currently does in protectNodeModules plugin.

callThrough in rewiremock/node

I'm trying to replace one method of a dependency using rewiremock/node (version 3.13.0) and callThrough().with(stubs). However, the module under test gets the mocked dependency replaced entirely by stubs. Calling a non-stubbed method of the dependency fails because the method isn't available.

The code is something like this:

A dependency

module.exports = {
  doOneThing() {
  },
  doAnotherThing() {
  }
};

Module under test

const dependency = require('./dependency');

module.exports = {
  methodUnderTest() {
    dependency.doOneThing();
    dependency.doAnotherThing();
  }
};

Mocha test

const rewiremock = require('rewiremock/node');
let serviceUnderTest;
let stubs;

beforeEach(function() {
  stubs = {
    doOneThing: sinon.stub()
  }; 
  serviceUnderTest= rewiremock.proxy(
    './service-under-test',
      r => ({
        './dependency': r.callThrough().with(stubs)
      })
  );
  
  // Does not work either!
  // rewiremock.enable();
  // rewiremock('./dependency')
  //  .callThrough()
  //  .with(stubs);
  // serviceUnderTest = require('./service-under-test');
  // rewiremock.disable();  
});

it('should call dependency.doAnotherThing', function () {
   serviceUnderTest.methodUnderTest(); // fails because dependency.doOneThing is not a function (but undefined)
});

Am I doing something wrong? Or is there someting wrong with how .callThrough() works with NodeJS (version 10) require?

Storybook integration not working

Hi,

I'm trying to use rewiremock inside my storybook with react project, but is not working.

I only get a error in the console, but not a useful one.

TypeError: "parent is undefined"
    _resolveFilename module.js:9
    _resolveFilename module.js:60
    fileNameTransformer nodejs.js:18
    resultName plugins.js:39
    convertName plugins.js:37
    mockModule mockModule.js:70
    proxy mockModule.js:181
    proxy mockModule.js:180
    inScope mockModule.js:222
    proxy mockModule.js:177
    js index.js:5
    js main.fea5ca72b2eb7cf739c0.bundle.js:52
    Webpack 18

I tried in a clean environment with a fresh installs and the error still persists

Clean Reproduction Repo: https://github.com/saintplay/rewiremock-storybook-bug

I didn't forget to add the three plugins required, and the babel plugin.

Steps to Reproduce

  • yarn install
  • yarn storybook
  • Open localhost:9009 (no build error, but runtime error)

Hope you can help to solve this use case, thanks

UPDATE

After some tweaking I managed to get this working. Example code here

Mocking .json file that doesn't exist in test environment

Hi @theKashey I have a .json config file that holds private keys that I should not add to my repo. When I make a commit my build pipeline runs tests, but it throws an error because it doesn't find the .json config file.

My thought was I can just mock it. So I tried:

rewiremock('../config.json').by('./mocks/config.json')

However this doesn't work, and throws an error saying it can't find the config.json file. It looks like the real config.json file needs to be there in order for me to mock it.

Is there some way I can write a mock where this file doesn't need to actually exist? Thanks in advance

It is not possible to mock non-existing files(?)

I can not figure out why

rewiremock('../something').with({});
console.log(require('../something')); // module '../something' does not exit

does not work but

rewiremock('../existing').with({});
console.log(require('../existing')); // {}

does.

Is it possible to mock files that do not yet exist like for example mock-require does?

mockRequire('../something', {});
console.log(require('../something')); // {}

Disable cache control

It's possible to skip cache wiping phase for for directChildOnly mocks, which may greatly speedup execution, and solve solve dependency problems.

  • directChildOnly should not touch cache
  • allowCallThrough should wipe cache

Not working in Babel v8

After updating to Babel 7 the web pack build no longer works.

Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Plugin/Preset files are not allowed to export objects, only functions. In /Users/chuckcarpenter/Projects/lift-anonymous/node_modules/rewiremock/babel.js
    at createDescriptor (/Users/chuckcarpenter/Projects/lift-anonymous/node_modules/@babel/core/lib/config/config-descriptors.js:178:11)
    at items.map (/Users/chuckcarpenter/Projects/lift-anonymous/node_modules/@babel/core/lib/config/config-descriptors.js:109:50)

Unable to mock function using proxy

Hi,

I am very new to this so I may be running into this issue.
I have an entry module app.js which imports a different module which I need to mock for my tests.
So app.js is a class extending react component.
and the module I want to stub exports a default function.
I am not able to get this working and keep hitting an error: Cannot read property 'call' of undefined.

Below is my code:

describe('HTMLUITests', () => {
  it('Init should initialize correctly', () => {
    var urlParams = {port: '13871', storeId: '51105455', locale: 'en', os: 'Windows'};
    var getUrlVars = function(location) { return urlParams; }

     const f = rewiremock.proxy('../src/app', {
       './UrlParameters' : getUrlVars
     });
   });
});

The error I get is

 TypeError: Cannot read property 'call' of undefined
        at __webpack_require__ (test-bundles/runtime.js:783:30)
        at Array.fn (test-bundles/runtime.js:151:20)
        at baseLoader (test-bundles/commons.js:116023:39)
        at Object.mockLoader [as _load] (test-bundles/commons.js:113697:72)
        at RQ (test-bundles/commons.js:116031:16)
        at requireModule (test-bundles/commons.js:113463:12)
        at Object.require (test-bundles/commons.js:114704:75)
        at Function.push../node_modules/rewiremock/es/mockModule.js.mockModule.requireActual (test-bundles/commons.js:114461:58)
        at test-bundles/commons.js:114317:27
        at Function.push../node_modules/rewiremock/es/mockModule.js.mockModule.inScope (test-bundles/commons.js:114353:5)
        at Function.push../node_modules/rewiremock/es/mockModule.js.mockModule.proxy (test-bundles/commons.js:114310:14)
        at Context.<anonymous> (test-bundles/htmlui-test.js:66:34)

Any help is appreciated !
Thanks
Trupti.

An in-range update of webpack-dev-server is breaking the build 🚨

The devDependency webpack-dev-server was updated from 3.2.0 to 3.2.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

webpack-dev-server is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci: Your tests are queued behind your running builds (Details).
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v3.2.1

3.2.1 (2019-02-25)

Bug Fixes

  • deprecation message about setup now warning about v4 (#1684) (523a6ec)
  • regression: allow ca, key and cert will be string (#1676) (b8d5c1e)
  • regression: handle key, cert, cacert and pfx in CLI (#1688) (4b2076c)
  • regression: problem with idb-connector after update internal-ip (#1691) (eb48691)
Commits

The new version differs by 9 commits.

  • bf99c26 chore(release): 3.2.1
  • eb48691 fix(regression): problem with idb-connector after update internal-ip (#1691)
  • 4b2076c fix(regression): handle key, cert, cacert and pfx in CLI (#1688)
  • 21687c3 refactor: utils (#1682)
  • 523a6ec fix: deprecation message about setup now warning about v4 (#1684)
  • 884fac0 refactor: remove invalid todo (#1683)
  • a2e5d12 refactor: CLI args and more tests (#1679)
  • 66129a8 test(Util, Validation): close server each time test ends (#1680)
  • b8d5c1e fix: allow ca, key and cert will be string (regression) (#1676)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Error importing `path`

When index.js says import path from 'path';, it seems to get transpiled as import path from "../../../path";, which produces a 404 error in Chrome running Polymer 3 (Node 8.15.0).

Any suggestion to get the package working?

Native ESM modules support

  • works with esm package - #24

    • Works with .module or mockery format.
    • Not working for .mjs files
  • works with native node 12 modules

    • No, it does not work. There is no parent-child connection, and, basically, even `import rewiremock from 'rewiremock' is not working'.
        1. default export is not working
        1. no module.parent is defined (at translators / 'commonjs')

webpack 4.2.0

It is the awesome testing library, it very helped me to test vuex store. But I updated webpack to version 4 and getting now:

(node:15400) DeprecationWarning: Tapable.plugin is deprecated. Use new API on .hooks instead
(node:15400) DeprecationWarning: Compilation.moduleTemplate: Use Compilation.moduleTemplates.javascript instead

Thank you for this tool!

Support custom webpack config filenames on webpackAlias plugin.

I am trying to use my webpack aliases with rewiremock as described in README.md

However, I get the following error:

  1) LazyImg
       binds classes with styles:
     Error: Cannot find any of these configuration files: webpack.config.js, webpack.config.babel.js
      at readAliases (node_modules/rewiremock/es/plugins/common/aliases.js:55:1)
      at configure (node_modules/rewiremock/es/plugins/webpack-alias.js:7:1)
      at Object.fileNameTransformer (node_modules/rewiremock/es/plugins/webpack-alias.js:12:1)
      at node_modules/rewiremock/es/plugins.js:21:1
      at Array.reduce (<anonymous>)
      at convertName (node_modules/rewiremock/es/plugins.js:19:1)
      at mockModule (node_modules/rewiremock/es/mockModule.js:37:1)
      at node_modules/rewiremock/es/mockModule.js:145:1
      at Array.forEach (<anonymous>)
      at node_modules/rewiremock/es/mockModule.js:144:1
      at Function.__dirname../node_modules/rewiremock/es/mockModule.js.mockModule.inScope (node_modules/rewiremock/es/mockModule.js:186:1)
      at Function.__dirname../node_modules/rewiremock/es/mockModule.js.mockModule.proxy (node_modules/rewiremock/es/mockModule.js:143:1)
      at Context.<anonymous> (src/webapp/app/components/LazyImg/LazyImg.spec.jsx:13:36)

It looks like rewiremock plugins need to accept configuration so we can point webpackAlias plugin to the correct webpack config instead of depending on the default config options 'webpack.config.js' and 'webpack.config.babel.js' seen here.

I am willing to help out, but wanted to run this by you before attempting to make a PR in case you have any ideas on how to support this.

An in-range update of karma-webpack is breaking the build 🚨

The devDependency karma-webpack was updated from 3.0.4 to 3.0.5.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

karma-webpack is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • βœ… ci/circleci: Your tests passed on CircleCI! (Details).
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v3.0.5

2018-09-14

Bug Fixes

  • karma-webpack: handle multiple outputs correctly (#357) (59de62c)
Commits

The new version differs by 2 commits.

  • 670f153 chore(release): 3.0.5
  • 59de62c fix(karma-webpack): handle multiple outputs correctly (#357)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of webpack is breaking the build 🚨

The devDependency webpack was updated from 4.19.0 to 4.19.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

webpack is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • βœ… ci/circleci: Your tests passed on CircleCI! (Details).
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v4.19.1

Bugfixes

  • Internal requested filename for import() with target: "electron-main" uses correct path separator on windows
    (This fixes a problem with filemappings in vscode)
  • devtool: "source-map" and variants generate SourceMaps when output file is .mjs
  • browser field as object is used when using target: "electron-renderer"
  • Comments near export default are preserved
  • Passing an array as externals value, now works correctly as documented
Commits

The new version differs by 15 commits.

  • b7121c1 4.19.1
  • ab28497 Merge pull request #8043 from RubenVerborgh/externals-object-array
  • 9bda629 remove bad unit test
  • f0271d9 fix ExternalModule and test case
  • 3aef0e5 Allow array as value in externals object.
  • 7b91fa6 Merge pull request #8042 from webpack/bugfix/comments-export-default
  • e08f71c keep/restore comments in export default
  • 2f78aae Merge pull request #8038 from sharang-d/patch-5
  • bb4c2d1 Correctly set the 'browser' value for electron-renderer
  • 5ade574 Merge pull request #7947 from philipwalton/mjs-sourcemap-support
  • 5258471 Merge pull request #8035 from kwonoj/fix-path
  • 2df7b0c fix(nodemaintemplate): resolve async chunk path platform agnostic
  • 17fafd3 Fix lint errors
  • a2cc031 Add tests for default source map extensions
  • 12762ff Add sourcemap support for .mjs output files

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Issues using with mocha-webpack

Hi, thanks for the hard work you have put into this project and the previous projects around the same problem-space!

I really want to use this library in my tests, but cannot get it to work at all. I receive:

TypeError: Cannot read property 'call' of undefined
    at __webpack_require__ (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/.tmp/mocha-webpack/1513799568611/webpack/bootstrap c5749b6d9b801abc09d7:637:1)
    at fn (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/.tmp/mocha-webpack/1513799568611/webpack/bootstrap c5749b6d9b801abc09d7:47:1)
    at Object../node_modules/mocha-webpack/lib/entry.js (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/.tmp/mocha-webpack/1513799568611/bundle.js:7289:73)
    at __webpack_require__ (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/.tmp/mocha-webpack/1513799568611/webpack/bootstrap c5749b6d9b801abc09d7:637:1)
    at /Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/.tmp/mocha-webpack/1513799568611/webpack/bootstrap c5749b6d9b801abc09d7:683:1
    at Object.<anonymous> (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/.tmp/mocha-webpack/1513799568611/bundle.js:687:10)
    at Module._compile (module.js:635:30)
    at Object._module2.default._extensions.(anonymous function) [as .js] (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/mocha-webpack/lib/util/registerRequireHook.js:147:12)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at /Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/mocha/lib/mocha.js:231:27
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/mocha/lib/mocha.js:228:14)
    at Mocha.run (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/mocha/lib/mocha.js:514:10)
    at /Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/mocha-webpack/lib/runner/TestRunner.js:198:25
    at Compiler.<anonymous> (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/mocha-webpack/lib/webpack/compiler/registerReadyCallback.js:26:7)
    at Compiler.applyPlugins (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/tapable/lib/Tapable.js:61:14)
    at emitRecords.err (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/webpack/lib/Compiler.js:264:11)
    at Compiler.emitRecords (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/webpack/lib/Compiler.js:371:38)
    at emitAssets.err (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/webpack/lib/Compiler.js:258:10)
    at applyPluginsAsyncSeries1.err (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/webpack/lib/Compiler.js:364:12)
    at next (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/tapable/lib/Tapable.js:218:11)
    at Compiler.compiler.plugin (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/webpack/lib/performance/SizeLimitsPlugin.js:99:4)
    at Compiler.applyPluginsAsyncSeries1 (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/tapable/lib/Tapable.js:222:13)
    at Compiler.afterEmit (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/webpack/lib/Compiler.js:361:9)
    at require.forEach.err (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/webpack/lib/Compiler.js:350:15)
    at /Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/async/dist/async.js:473:16
    at iteratorCallback (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/async/dist/async.js:1050:13)
    at /Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/async/dist/async.js:958:16
    at MemoryFileSystem.writeFile (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/memory-fs/lib/MemoryFileSystem.js:328:9)
    at writeOut (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/webpack/lib/Compiler.js:339:28)
    at require.forEach (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/webpack/lib/Compiler.js:345:12)
    at /Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/async/dist/async.js:3096:16
    at eachOfArrayLike (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/async/dist/async.js:1055:9)
    at eachOf (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/async/dist/async.js:1103:5)
    at Object.eachLimit (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/async/dist/async.js:3158:5)
    at emitFiles (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/webpack/lib/Compiler.js:315:21)
    at Immediate.<anonymous> (/Users/alexkrautmann/repos/git.cars.com/npm/react-shop-app/node_modules/memory-fs/lib/MemoryFileSystem.js:288:4)
    at runCallback (timers.js:789:20)
    at tryOnImmediate (timers.js:751:5)
    at processImmediate [as _immediateCallback] (timers.js:722:5)

Here is my webpack config:

const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const postCssFlexbugsFixesPlugin = require('postcss-flexbugs-fixes');
const DotEnvPlugin = require('webpack-dotenv-extended-plugin');
const ReWireMockPlugin = require('rewiremock/webpack/plugin');

const publicPath = '/react-shop/webapp/static/';

const res = p => path.resolve(__dirname, p);

const externals = fs
    .readdirSync(res('../node_modules'))
    .filter(x => !/\.bin|react-universal-component|require-universal-module|webpack-flush-chunks/.test(x))
    .reduce((externalsAcc, mod) => {
        externalsAcc[mod] = `commonjs ${mod}`;
        return externalsAcc;
    }, {});

module.exports = {
    name: 'test',
    target: 'node',
    externals,
    devtool: 'inline-source-map',
    output: {
        publicPath,
        // use absolute paths in sourcemaps (important for debugging via IDE)
        devtoolModuleFilenameTemplate: '[absolute-resource-path]',
        devtoolFallbackModuleFilenameTemplate: '[absolute-resource-path]?[hash]',
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: 'babel-loader',
            },
            {
                test: /\.scss$/,
                use: [
                    {
                        loader: 'css-loader/locals',
                        options: {
                            modules: true,
                            localIdentName: '[name]__[local]--[hash:base64:5]',
                        },
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            // Necessary for external CSS imports to work
                            // https://github.com/facebookincubator/create-react-app/issues/2677
                            ident: 'postcss',
                            plugins: () => [
                                postCssFlexbugsFixesPlugin,
                                autoprefixer({
                                    browsers: [
                                        '>1%',
                                        'last 4 versions',
                                        'Firefox ESR',
                                        'not ie < 9', // React doesn't support IE8 anyway
                                    ],
                                    flexbox: 'no-2009',
                                }),
                            ],
                        },
                    },
                    { loader: 'sass-loader' },
                ],
            },
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            // no reason to emit file on the server since we serve static from buildClient
                            emitFile: false,
                            publicPath,
                        },
                    },
                ],
            },
            {
                test: /\.svg$/,
                use: [
                    {
                        // Uses default runtimeGenerator for target=node
                        loader: 'svg-sprite-loader',
                    },
                ],
            },
        ],
    },
    resolve: {
        extensions: ['.js', '.jsx'],
        alias: { 'cars-ui': 'cars-ui/dist/scss/' },
    },
    plugins: [
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new ReWireMockPlugin(),
        new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
        new DotEnvPlugin({
            errorOnMissing: true,
            errorOnExtra: true,
            schema: './src/webapp/env/.env.schema',
            defaults: './src/webapp/env/.env.defaults.development',
            path: './src/webapp/env/local/.env.dev',
        }),
    ],
};

And I launch this all with (very long) npm script:

"check-test:webapp": "cross-env NODE_ENV=test mocha-webpack --require jsdom-global/register --require babel-polyfill --webpack-config webpack/config.test.js \"src/webapp/app/components/**/*.+(js|jsx)\" \"src/webapp/app/state/**/*.+(js|jsx)\" \"src/webapp/app/pages/**/*.+(js|jsx)\" \"src/webapp/services/**/*.+(js|jsx)\" \"src/webapp/universal/**/*.+(js|jsx)\"",

I have tried the following uses of .proxy:

describe('LazyImg', () => {
    it('binds classes with styles', () => {
        const bindClassnamesStub = sinon.stub().returns(() => {});
        const LazyImg = rewiremock.proxy(() => require('./LazyImg.component'), {
            'bind-classnames': bindClassnamesStub,
        });
        shallow(<LazyImg src="foo.com/foo" alt="Foobar" lazyHeight={109} lazyWidth={182} />);
        expect(bindClassnamesStub).to.have.been.calledWith(styles);
    });
});
describe('LazyImg', () => {
    it('binds classes with styles', () => {
        const bindClassnamesStub = sinon.stub().returns(() => {});
        const LazyImg = rewiremock.proxy('./LazyImg.component', () => ({
            'bind-classnames': bindClassnamesStub,
        }));
        shallow(<LazyImg src="foo.com/foo" alt="Foobar" lazyHeight={109} lazyWidth={182} />);
        expect(bindClassnamesStub).to.have.been.calledWith(styles);
    });
});
describe('LazyImg', () => {
    it('binds classes with styles', () => {
        const bindClassnamesStub = sinon.stub().returns(() => {});
        const LazyImg = rewiremock.proxy('./LazyImg.component', {
            'bind-classnames': bindClassnamesStub,
        });
        shallow(<LazyImg src="foo.com/foo" alt="Foobar" lazyHeight={109} lazyWidth={182} />);
        expect(bindClassnamesStub).to.have.been.calledWith(styles);
    });
});

I have also tried adding various combinations of relative, nodejs, and webpackAlias plugins in my spec.helper.jsx (which is imported in every test and exports rewiremock).

I also tried with the the low level .enable and .disable as follows:

beforeEach(() => rewiremock.enable());
afterEach(() => rewiremock.disable());

I can use inject loader with require('inject-loader!./LazyImg.component''), but it cannot use isolation and I would prefer not to use require which would force me to make considerable changes to my eslint rules.

Isolation is not working

I have no idea why isolation is not working in my project.
I have two files:
Test file:

// process.env.NODE_ENV = 'test';

const HttpStatusCode = require('http-statuscode');
const chai = require('chai');
const chaiHttp = require('chai-http');
const rewiremock = require('rewiremock').default

const should = chai.should();

chai.use(chaiHttp);

const db_mock = require('./mock/db_mock');

rewiremock('../lib/db')
    .with(db_mock);

rewiremock.enable();
rewiremock.isolation();
rewiremock.passBy(/node_modules/);

const app = require('../src/app');
// const route = require('../src/route/index');

rewiremock.withoutIsolation();
rewiremock.disable();

App file:

const express = require('express');
const path = require('path');

const app = express();

const db = require("./lib/db");
const test = require("./route/test");
const api = require("./route/api");
const www = require("./route");

// TODO: use here express.static when we would have lots of files
app.get('/static/item_db.css', function (req, res) {
  res.sendFile(path.resolve(__dirname, "./public/item_db.css"));
});

app.use('/', www);
app.use('/api', api);

db.refresh();

test()

module.exports = app;

As we can see test route is NOT mocked, but isolation does not care about this.

Overriding same module dependencies

This looks interesting but I'm rather new to dependency injection in JS and I have a question.

I was wondering if there was a way for me to override a function from within the same module? I am doing something similar to this:

// module.js
export default {
  doA,
  doB
};

export function doA() {
  const b = doB();
  return "a" + b;
}

export function doB() {
  return "b";
}
// test.js
import rewiremock from "rewiremock";
import { expect } from "chai";

describe("moduleTest", function() {
  it("adds a", function() {
    // mock setup
    rewiremock("./module")
      .callThrough()
      .with({
        doB: () => "a"
      });

    rewiremock.enable();

    const mockedModule = require("./module");
    expect(mockedModule.doA()).to.equal("aa");

    rewiremock.disable();
  });
});

This test will fail for me returning "ab" in node 8.9.3. What am I doing wrong?

Any comment is appreciated, thank you!

Property 'default' added to stubs when proxying using rewiremock/node

I'm doing something like this in a Node.js Mocha test

const rewiremock = require('rewiremock/node').default
const myService = rewiremock.proxy('path/to/service', {
   'path/to/data': dataStub
});

where dataStub is an data object. myService goes through each key of dataStub. Now, rewiremock adds an extra property default to the stubs. This interferes with what the service is doing.

Is there a way to prevent rewiremock from adding that extra default property to a stub? Should it do this at all in a Node.js environment?

How to simply mock a child react component?

Say I want to unit test component "Account". It is

class Account extends Component {
 render() {
   return(
  <Type>
     ....
   </Type>
);
}

And in my test, I want to mount Account like

const wrapper = mount(
         <MemoryRouter initialEntries={[ '/xxxxx' ]}>
            <Account/>
         </MemoryRouter>
)

I have a mocked the Type component. How to replace the real Type with my MockType? Tried several ways, not working. I am pretty new. Thanks for any help

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.