在Angular 2中加载带有SystemJS和Karma的节点模块

dch*_*cke 10 karma-runner systemjs angular

我正在使用Angular 2,SystemJS和Karma构建一个Web应用程序进行测试.

我正在尝试在测试中加载节点模块ngrx/store:

import {
  it, describe, expect, beforeEach, inject
} from 'angular2/testing';

import { Store } from '@ngrx/store';

describe('Graphs store', () => {
  let graphs;

  beforeEach(inject([Store], (store: Store<any>) => {
    graphs = store.select('graphs');
  }));

  it('works', () => {
    // expect graphs to do something...
  });
});
Run Code Online (Sandbox Code Playgroud)

但是,我的测试失败并显示以下消息:

404: /@ngrx/store
Chrome 48.0.2564 (Mac OS X 10.11.3) ERROR
  Error: XHR error (404 Not Found) loading http://localhost:9876/@ngrx/store
Run Code Online (Sandbox Code Playgroud)

我在dev中也遇到了同样的问题,结果发现SystemJS不知道在哪里可以找到@ngrx/store.为了解决这个问题,我这样做了:

System.config({
  packages: {
    src: {
      format: 'register',
      defaultExtension: 'js'
    }
  },
  map: { '@ngrx/store' : 'node_modules/@ngrx/store/dist/store.js' } // <-- this
});
Run Code Online (Sandbox Code Playgroud)

我修改了我的Karma shim文件来做同样的事情.在第二次运行测试后,我现在得到一个不同的错误:

404: /node_modules/@ngrx/store/dist/store.js
Chrome 48.0.2564 (Mac OS X 10.11.3) ERROR
  Error: XHR error (404 Not Found) loading http://localhost:9876/node_modules/@ngrx/store/dist/store.js
Run Code Online (Sandbox Code Playgroud)

这意味着它必须采用我给它的显式路径,但它仍然找不到模块.但是,它是模块的正确路径,并且在加载到浏览器中时可以正常工作.

我很遗憾下次要做什么.有人能指出我正确的方向吗?

有几点需要注意:

  • 将节点模块添加到Karma的files数组不是一个选项,因为它的依赖关系需要使用SystemJS来解决
  • 这仅适用于SystemJS需要关于它们所在位置的自定义指令的节点模块.我可以在我的测试中加载其他模块,而不需要提供特定的位置,因为SystemJS能够找到它

这是我的Karma配置:

// Set up with the help of
// http://twofuckingdevelopers.com/2016/01/testing-angular-2-with-karma-and-jasmine/

module.exports = function(config) {
  config.set({

    basePath: '.',

    frameworks: ['jasmine'],

    files: [
      // paths loaded by Karma
      {pattern: 'node_modules/angular2/bundles/angular2-polyfills.js', included: true, watched: true},
      {pattern: 'node_modules/systemjs/dist/system.src.js', included: true, watched: true},
      {pattern: 'node_modules/rxjs/bundles/Rx.js', included: true, watched: true},
      {pattern: 'node_modules/angular2/bundles/angular2.dev.js', included: true, watched: true},
      {pattern: 'node_modules/angular2/bundles/testing.dev.js', included: true, watched: true},
      {pattern: 'karma-test-shim.js', included: true, watched: true},

      // paths loaded via module imports
      {pattern: 'src/**/*.js', included: false, watched: true},

      // paths to support debugging with source maps in dev tools
      {pattern: 'src/**/*.ts', included: false, watched: false},
      {pattern: 'src/**/*.js.map', included: false, watched: false}
    ],

    // proxied base paths
    proxies: {
      // required for component assets fetched by Angular's compiler
      '/src/': '/base/src/'
    },

    port: 9876,

    logLevel: config.LOG_INFO,

    colors: true,

    autoWatch: true,

    browsers: ['Chrome'],

    // Karma plugins loaded
    plugins: [
      'karma-jasmine',
      'karma-coverage',
      'karma-chrome-launcher'
    ],

    // // Coverage reporter generates the coverage
    // reporters: ['progress', 'dots', 'coverage'],
    //
    // // Source files that you wanna generate coverage for.
    // // Do not include tests or libraries (these files will be instrumented by Istanbul)
    // preprocessors: {
    //   'src/**/!(*spec).js': ['coverage']
    // },

    // coverageReporter: {
    //   reporters:[
    //     {type: 'json', subdir: '.', file: 'coverage-final.json'}
    //   ]
    // },

    singleRun: true
  })
};
Run Code Online (Sandbox Code Playgroud)

这是我的Karma垫片:

// Tun on full stack traces in errors to help debugging
Error.stackTraceLimit = Infinity;

jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;

// // Cancel Karma's synchronous start,
// // we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function() {};

System.config({
  packages: {
    'base/src': {
      defaultExtension: 'js',
      format: 'register',
      map: Object.keys(window.__karma__.files).filter(onlyAppFiles).reduce(createPathRecords, {})
    }
  },
  // This makes it work in the browser, but not in my tests!
  paths: { '@ngrx/store' : 'node_modules/@ngrx/store/dist/store.js' }
});

System.import('angular2/src/platform/browser/browser_adapter')
  .then(function(browser_adapter) { browser_adapter.BrowserDomAdapter.makeCurrent(); })
  .then(function() { return Promise.all(resolveTestFiles()); })
  .then(function() { __karma__.start(); }, function(error) { __karma__.error(error.stack || error); });

function createPathRecords(pathsMapping, appPath) {
  // creates local module name mapping to global path with karma's fingerprint in path, e.g.:
  // './vg-player/vg-player':
  // '/base/src/vg-player/vg-player.js?f4523daf879cfb7310ef6242682ccf10b2041b3e'
  var pathParts = appPath.split('/');
  var moduleName = './' + pathParts.slice(Math.max(pathParts.length - 2, 1)).join('/');
  moduleName = moduleName.replace(/\.js$/, '');
  pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath];
  return pathsMapping;
}

function onlyAppFiles(filePath) {
  return /\/base\/src\/(?!.*\.spec\.js$).*\.js$/.test(filePath);
}

function onlySpecFiles(path) {
  return /\.spec\.js$/.test(path);
}

function resolveTestFiles() {
  return Object.keys(window.__karma__.files)  // All files served by Karma.
    .filter(onlySpecFiles)
    .map(function(moduleName) {
      // loads all spec files via their global module names (e.g.
      // 'base/src/vg-player/vg-player.spec')
      return System.import(moduleName);
    });
}
Run Code Online (Sandbox Code Playgroud)

更新

有一个与错误的例子库在这里.您可以在此处查看导致错误的特定更改.运行$ npm install$ npm test获取错误.

Sas*_*sxa 8

包括@ngrx/store其他捆绑包,将解决404错误

    // for testing in karma.conf.js
    files: [
        // paths loaded by Karma
        {pattern: 'node_modules/@ngrx/store/dist/store.js', included: true, watched: true},
    ],
Run Code Online (Sandbox Code Playgroud)

但与编译为System模块的其他bundle不同,@ngrx/store编译为commonjs模块

// 'node_modules/angular2/bundles/angular2.dev.js'
"format register";
System.register("angular2/src/facade/lang", [], true, function(require, exports, module) {
....

// 'node_modules/rxjs/bundles/Rx.js'
"format register";
System.register("rxjs/util/root", [], true, function(require, exports, module) {
....

// 'node_modules/@ngrx/store/dist/store.js'
....
var Observable_1 = require('rxjs/Observable');
....
Run Code Online (Sandbox Code Playgroud)

这会导致错误:

未捕获的ReferenceError:未定义require

// with {pattern: '~/store.js', indluded: true}
// context.html includes
<script type="text/javascript" src="/base/node_modules/@ngrx/store/dist/store.js?fb5e807149603c3c2f998c98faf6826c7e301d71"></script>
Run Code Online (Sandbox Code Playgroud)

这就是你不应该包括它的原因:

{pattern: 'node_modules/@ngrx/store/dist/store.js', included: false, watched: true}
Run Code Online (Sandbox Code Playgroud)

这基本上会将它列在window.__karma__.files对象中,但不会将其作为脚本添加到karma中context.html- 浏览器不会加载并运行导致错误的代码.加载应由SystemJS处理......

如果你运行karma测试,singleRun: false你可以检查Chrome的Devtools> Network中的文件.你会看到一个已加载文件的列表,这就是最后一块拼图的位置:

在你的karma-test-shim.js改变System.config.map:

map: { '@ngrx/store' : '/base/node_modules/@ngrx/store/dist/store.js' }
Run Code Online (Sandbox Code Playgroud)

执行4次成功中的4次(0.037秒/0.008秒)