我正在尝试使用我的Karma(Webpack Typescript)单元测试重新连接.我的单元测试用Typescript编写,与Webpack捆绑在一起,然后与Karma一起运行.我一直收到错误: PhantomJS 2.1.1 (Windows 7 0.0.0) ERROR Error:
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相同.
我所有不使用重新布线的测试工作正常.
这是我的测试文件:
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'] },我想你写错了
import rewire = require(“rewire”);
它应该是
import rewire from 'rewire'
对于ES6
要么
const rewire = require('rewire')
对于ES5