Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot find module "module" - Rewire.js

I am trying to use rewire with my Karma (Webpack + Typescript) unit tests. My unit tests are written in Typescript, bundled with Webpack, and then run with Karma. I keep getting the error:

PhantomJS 2.1.1 (Windows 7 0.0.0) ERROR
  Error: Cannot find module "module"
  at src/myTest.spec.ts:187

I looked into the code of Rewire, and the problem comes from the line

var Module = require("module"),

I know there is a Webpack Rewire plugin, but when I use it, I have the same problem as that already reported in an issue.

All my tests that don't use rewire work fine.

Here is my test file:

import rewire = require("rewire");
const decorators = rewire("./decorators");

describe('something', () => {
    it('should do something', () => {
        decorators.__set__('Test', () => 'hello');
        // In know this is pointless, but it's just to make sure that rewire works.
        expect(decorators.Test).toBe('hello');
    });
});

Here is my webpack config:

var webpack = require('webpack');
var path = require('path');
var fs = require('fs');

var nodeModules = {};
fs.readdirSync('node_modules')
    .filter(function (x) {
        return ['.bin'].indexOf(x) === -1;
    })
    .forEach(function (mod) {
        nodeModules[mod] = 'commonjs ' + mod;
    });

// Our Webpack Defaults
var webpackConfig = {
    entry: './src/index.ts',
    target: 'node',
    module: {
        loaders: [
            {test: /\.ts$/, loaders: ['ts-loader'], exclude: /node_modules/}
        ]
    },
    plugins: [
        new webpack.BannerPlugin({banner: 'require("source-map-support").install();', raw: true, entryOnly: false}),
        new webpack.optimize.UglifyJsPlugin({sourceMap: true}),
        new webpack.optimize.AggressiveMergingPlugin(),
    ],
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'index.js',
        sourceMapFilename: 'index.map'
    },
    externals: nodeModules,
    devtool: 'source-map',
    resolve: {
        extensions: ['.ts', '.js']
    }
};

module.exports = webpackConfig;

and here is my (the relevant) part of my karma.conf.js:

frameworks: ['jasmine'],
files: [
    'src/**/*.spec.ts',
    'test/**/*.ts'
],
exclude: [],
webpack: {
    devtool: webpackConfig.devtool,
    module: webpackConfig.module,
    resolve: webpackConfig.resolve,
},
webpackMiddleware: {
    quiet: true,
    stats: {
        colors: true
    }
},
preprocessors: {
    'src/**/*.spec.ts': ['webpack', 'sourcemap'],
    'test/**/*.ts': ['webpack', 'sourcemap']
},
like image 392
user5365075 Avatar asked Sep 13 '17 09:09

user5365075


People also ask

How do I rewire in node JS?

First we load rewire, then we use it to load the code that we want to test. var rewire = require("rewire"); var parseCsv = rewire('../source/convert. js'); By loading the code this way, we gain the ability to mock certain features of the code.

What is rewire NPM?

rewire adds a special setter and getter to modules so you can modify their behaviour for better unit testing. You may. inject mocks for other modules or globals like process. inspect private variables. override variables within the module.

How to resolve cannot find module error when using rewire?

rewire uses module module (can be used by require ('module') ), which ts-jest does not wrap. Therefore, rewire resolves the module you importing without typescript functionality, only searching for the file with .js extension. This results in Cannot find module error since the target *.js file does not exist.

How to solve cannot find module 'internal/modules/CJS/loader' error?

To solve the error Cannot find module 'internal/modules/cjs/loader.js', make sure you are pointing the node command to a file that exists on your file system, delete node_modules and package-lock.json, re-install dependencies and restart your IDE. The first thing you need to check is that you run the node command pointed to a file that exists.

What does “cannot find module” mean?

To conclude, the error “Cannot find module” happens when Node.js can’t find the module that a file is trying to import. You can see the file and the module that’s causing the issue from the error output generated by Node itself.

How do I resolve the cannot find module error in NPM?

The cannot find module error occurs because NPM cannot find the module required by the index.js file. In this case, the axios module. To resolve the error, you need to make sure that axios is installed in the node_modules/ folder. Please note that the node_modules/ folder must be located in the same directory as the index.js file:


1 Answers

I think you write this wrong import rewire = require("rewire");

it should be

import rewire from 'rewire' 

for ES6 or

const rewire = require('rewire')

for ES5

like image 81
Peak Sornpaisarn Avatar answered Oct 14 '22 03:10

Peak Sornpaisarn