我尝试在Karma(Webpack + Typescript)单元测试中使用rewire
。我的单元测试是用Typescript编写的,与Webpack捆绑在一起,然后与Karma一起运行。我一直收到错误:
PhantomJS 2.1.1 (Windows 7 0.0.0) ERROR
Error: Cannot find module "module"
at src/myTest.spec.ts:187
我看了Rewire的代码,问题出在行上
var Module = require("module"),
我知道有一个Webpack Rewire插件,但是当我使用它的时候,我遇到了和那个already reported in an issue一样的问题。
我所有不使用rewire
的测试都运行良好。
下面是我的测试文件:
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');
});
});
下面是我的webpack配置:
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;
下面是我的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']
},
2条答案
按热度按时间slhcrj9b1#
我认为你写这个错误的导入rewire = require("rewire");
应该是
对于ES6或
适用于ES5
w8f9ii692#
在package.json中重写脚本对我很有效:
如果您收到错误
语法错误:JSON中位置0处的意外标记
这为我解决了这个问题:
这不是我的主意。请看这个对Github问题的回答,以获得一个很好的解释。