如何让Karma + Webpack找到模块?

时间:2015-11-26 08:10:05

标签: javascript node.js karma-runner webpack

我希望在webpack通过Karma测试运行器将它们组合在一起后,在一堆模块上运行我的测试,但每当我运行我的测试时,Karma说,

  

"错误:找不到模块" hello.js"在   http://localhost:9877/base/src/hello.spec.js?d301966ffc1330826574d9d8fff5a644c3390c68:47"

我有一个spec文件:

var a = require('hello.js');

describe("a test test", function() {

  it("humperdink test", function() {
    expect(a).toEqual('humperdink');
  }); //end it

}); //end describe

hello.js是这样的:

var a = 'humperdink';

module.exports = a;

这两个文件都在同一个文件夹中。

我的karma.conf.js是:

module.exports = function (config) {
  config.set({
    frameworks: ['jasmine'],
    files: [
      'src/**/*.js',
      'tests/**/*.spec.js'
    ],
    preprocessors: {
      'tests/**/*.spec.js': ['webpack'],
      'src/**/*.js' : ['webpack']
    },
    browsers: ['PhantomJS'],
    webpack: {
      entry: './src/hello.spec.js',
      output: {
        filename: 'bundle.js'
      }
    },
    webpackMiddleware: {
      noInfo: true
    }
  })
};

目前我安装的devDependencies是

"devDependencies": {
    "jasmine-core": "^2.3.4",
    "jshint": "^2.8.0",
    "karma": "^0.13.15",
    "karma-jasmine": "^0.3.6",
    "karma-jshint-preprocessor": "0.0.6",
    "karma-phantomjs-launcher": "^0.2.1",
    "karma-webpack": "^1.7.0",
    "phantomjs": "^1.9.19",
    "sinon": "^1.17.2",
    "webpack": "^1.12.9"

如何让Karma找到hello.js模块?

我已尝试将规范文件的第一行更改为

之类的内容
require('hello.js');

require('./hello.js');

require('hello');

根据Karma Webpack - Error: Cannot find module "./test/utilities.js"

的建议

我不认为这里有任何过于复杂的事情,例如Cannot find module error when using karma-webpack

我已经检查过以确保Karma测试运行器正在运行。如果我在自己的文件中运行一个非常简单的测试,它就可以正常工作。

如何解决这个问题?

1 个答案:

答案 0 :(得分:9)

我已复制您的项目并进行修复。关注https://github.com/webpack/karma-webpack

在规范中:

var a = require('../src/hello.js');

karma.conf.js:

module.exports = function (config) {
  config.set({
    frameworks: ['jasmine'],
    files: [
      //'src/**/*.js', <-------- Remove or comment this
      'tests/**/*.spec.js'
    ],
    preprocessors: {
      'tests/**/*.spec.js': ['webpack'],
      'src/**/*.js' : ['webpack']
    },
    browsers: ['PhantomJS'],
    webpack: {
      entry: './tests/hello.spec.js',
      output: {
        filename: 'bundle.js'
      }
    },
    webpackMiddleware: {
      noInfo: true
    }
  })
};

karma specs result in terminal

另外还有 npm test 命令: 在package.json中:

"scripts": {
    "test": "./node_modules/karma/bin/karma start"
}
相关问题