无法使用Karma Webpack查找在测试文件中导入的模块

时间:2017-04-22 09:11:51

标签: angularjs karma-jasmine karma-webpack isparta

我收到以下错误:

  

在运行karma,src / controllers中的控制器文件,src / tests中的测试文件

时找不到模块“../controllers/loginCtrl”

1)karma.conf.js:

var path = require('path');
var hasCoverage = global.process.argv.reduce(function (result, arg) {
  return arg.indexOf('coverage') !== -1 || result;
});

var include = [
  path.resolve('./src')
];

var preLoaders = hasCoverage ? [

// Process test code with Babel
{test: /\.spec\.js$/, loader: 'babel', include: include},

// Process all non-test code with Isparta
{test: /\.js$/, loader: 'isparta', include: include, exclude:   /\.spec\.js$/}
] : [
{test: /\.js$/, loader: 'babel', include: include}
];
var loaders = [
 {test: /\.sass$/, loader: 'style!css?sourceMap!sass?sourceMap&indentedSyntax=true'},
 {test: /\.png$/, loader: 'null'},
 {test: /\.jpg$/, loader: 'null'},

 // Loader for JSON, may be used in some tests
 {test: /\.json$/, loader: 'json'},

 // Need some real loaders for HTML, because angular directives are coupled with templates
 {test: /\.haml$/, loader: 'hamlc-loader'},
 {test: /\.html$/, loader: 'ng-cache?prefix=[dir]/[dir]'}
];


module.exports = function (config) {
   config.set({
   basePath: '',
   frameworks: ['jasmine'],
   plugins: [
    'karma-babel-preprocessor',
    'karma-jasmine',
    'karma-webpack',
    'karma-phantomjs-launcher',
    'karma-chrome-launcher',
  ],
  files: [
    'spec.js',
  ],
  webpack: {
    devtool: 'eval',
    module: {
      loaders: loaders,
      preLoaders: preLoaders
    },
    cache: true
  },
  webpackMiddleware: {
    stats: {
      chunkModules: false,
      colors: true
    }
  },
  preprocessors: {
    'spec.js': ['webpack'],
  },
  babelPreprocessor: {
    options: {
      presets: ['es2015'],
      sourceMap: 'inline'
    },
    filename: function (file) {
      return file.originalPath.replace(/\.js$/, '.es5.js');
    },
    sourceFileName: function (file) {
      return file.originalPath;
    }
  },
  port: 9876,
  colors: true,
  logLevel: config.LOG_INFO,
  autoWatch: false,
  browsers: ['PhantomJS'],
  singleRun: true
  });
};

2)spec.js:

var testsContext;

require('babel-polyfill');
require('angular');
require('angular-mocks');

testsContext = require.context('./src/', true, /\.spec\.js$/);
testsContext.keys().forEach(testsContext);

3)LoginCtrl.spec.js:

import LoginCtrl from '../controllers/loginCtrl';
describe('controller: LoginCtrl', function() {
  let scope;
  let ctrl;

  beforeEach(function() {
    angular.module('envio', [])
       .controller('LoginCtrl', LoginCtrl);
  });

  beforeEach(angular.mock.module('envio'));

  beforeEach(angular.mock.inject(function($controller, $rootScope) {
    scope = $rootScope.$new();

    ctrl = $controller('LoginCtrl', {
     $scope: scope
    });
  }));

  it('should set message to null', function() {

    expect(ctrl).toBeDefined();
    // expect(scope.message).toBeNull();
  });
});

如何防止此错误?

0 个答案:

没有答案