【问题标题】:How can I get Karma + Webpack to find the module?如何让 Karma + Webpack 找到模块?
【发布时间】:2016-02-29 05:47:45
【问题描述】:

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

“错误:在以下位置找不到模块“hello.js” http://localhost:9877/base/src/hello.spec.js?d301966ffc1330826574d9d8fff5a644c3390c68:47"

我有一个规格文件:

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 测试运行程序正常工作。如果我在自己的文件中运行一个非常简单的测试,它就可以正常工作。

我该如何解决这个问题?

【问题讨论】:

  • 你试过require('../src/hello');吗?
  • 在我将两个文件移动到同一个目录之前,我做到了。

标签: javascript node.js karma-runner webpack


【解决方案1】:

我已复制您的项目并修复它。关注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
    }
  })
};

另外对于 npm test 命令: 在 package.json 中:

"scripts": {
    "test": "./node_modules/karma/bin/karma start"
}

【讨论】:

    猜你喜欢
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多