【问题标题】:Karma cannot load imported filesKarma 无法加载导入的文件
【发布时间】:2016-07-28 11:23:53
【问题描述】:

我已经挣扎了好几天了,因为我无法使用 Karma 进行任何真正的测试。我可以运行不需要导入的测试(例如基本的健全性测试),但是一旦我必须从我的应用程序中导入一些东西,我就会收到错误:

system.src.js:1085 GET http://localhost:9876/base/dist/components/test.service404(未找到)fetchTextFromURL @system.src.js:1085(匿名函数)@system.src.js:1646ZoneAwarePromise @angular2-polyfills.js:589(匿名函数)@system.src.js:1645(匿名函数)@system.src.js:2667(匿名函数)@system.src.js:3239(匿名函数)@system.src.js:3506(匿名函数) @system.src.js:3888(匿名函数)@system.src.js:4347(匿名函数)@system.src.js:4599(匿名函数)@system.src.js:337ZoneDelegate.invoke@angular2-polyfills .js:332Zone.run @ angular2-polyfills.js:227(匿名函数) @ angular2-polyfills.js:576ZoneDelegate.invokeTask @ angular2-polyfills.js:365Zone.runTask @ angular2-polyfills.js:263drainMicroTaskQueue @ angular2-polyfills .js:482ZoneTask.invoke @ angular2-polyfills.js:434 angular2-polyfills.js:469 未处理的承诺拒绝:karma.error 不是函数;区域:;任务:Promise.then;值:TypeError:karma.error 不是函数(…)consoleError @ angular2-polyfills.js:469drainMicroTaskQueue @ angular2-polyfills.js:498ZoneTask.invoke @ angular2-polyfills.js:434 angular2-polyfills.js:471 错误:未捕获(承诺):TypeError:karma.error 不是函数(…)

我需要提一下: 示例测试:

import { provide } from 'angular2/core';
import {TestService} from './test.service';
import {
//   beforeEach,
  beforeEachProviders,
  describe,
  expect,
  it,
  inject,
//   injectAsync
} from 'angular2/testing';

 describe('TestService', () => {

  beforeEachProviders(() => [
    provide(TestService, {useClass: TestService})
  ]);
  it('should say hello with name', inject([TestService], (testService: TestService) => {
    expect(testService.name).toBe('Injected Service');
  }));

  it('should say hello with name', () => {
    expect(true).toBe(true);
  });

});

我的项目结构是基于多模块的:

Karma.conf.js:

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.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 },
    { pattern: 'dist/components/matchers.js', included: true, watched: true },

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

    // paths loaded via Angular's component compiler
    // (these paths need to be rewritten, see proxies section)
    { pattern: 'dist/*.html', included: false, watched: true },
    { pattern: 'dist/styles/*.css', included: false, watched: true },
    { pattern: 'dist/components/**/*.html', included: false, watched: true },
    { pattern: 'dist/components/**/*.css', included: false, watched: true },

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

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

karma-test-shim.js:

...

System.config({
    packages: {
        'base/src': {
            defaultExtension: false,
            format: 'register',
            map: Object.keys(window.__karma__.files).
                filter(onlyAppFiles).
                reduce(function createPathRecords(pathsMapping, appPath) {
                    // creates local module name mapping to global path with karma's fingerprint in path, e.g.:
                    // './hero.service': '/base/src/app/hero.service.js?f4523daf879cfb7310ef6242682ccf10b2041b3e'
                    var moduleName = appPath.replace(/^\/base\/src\//, './').replace(/\.js$/, '');
                    pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath]
                    return pathsMapping;
                }, {})

        }
    }
});


function filePath2moduleName(filePath) {
    console.log('filePath2moduleName', filePath)
    return filePath.
        replace(/^\//, '').              // remove / prefix
        replace(/\.\w+$/, '');           // remove suffix
}


function onlyAppFiles(filePath) {
    console.log('filePath', filePath)
    return /^\/base\/src\/.*\.js$/.test(filePath)
}


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

非常欢迎任何想法!

【问题讨论】:

  • 而你的ts文件编译到dist文件夹下?对吗?

标签: angular karma-jasmine


【解决方案1】:

如果您将 TS 文件编译到 dist 文件夹中,我认为您有差距。我会在您的 karma-test-shim.js 文件中尝试以下操作:

System.config({
  packages: {
    'base/dist': {
        defaultExtension: false,
        format: 'cjs',
        map: Object.keys(window.__karma__.files).filter(onlyAppFiles).reduce(createPathRecords, {})
    }
  }
});

(...)

function createPathRecords(pathsMapping, appPath) {
  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;
}

createPathRecords 函数中的以下行看起来很奇怪,因为您不应该拥有来自 src 而是来自 dist 的文件。

使用此代码,我生成了以下 SystemJS 配置(map 块):

System.config({
  packages: {
    'base/dist': {
      defaultExtension: false,
      format: 'register',
      map: {
        './comps/my-list': '/base/dist/comps/my-list.js?e9(...)',
        './dist/my-app': '/base/dist/my-app.js?fe(...)',
        './pipes/my-pipe': '/base/dist/pipes/my-pipe.js?78(...)',
        './services/http-service': '/base/dist/services/http-service.js?c1(...)',
        './services/my-service': '/base/dist/services/my-service.js?b1(...)'
      }
    }
  }
});

在您的情况下,/base/dist/components/test.service 无法通过 SystemJS 解析,所以我猜您的 map 块不正确或 packages 的条目不正确。

请注意,map 块的条目与 packages 的键相关。在您的情况下,我猜您生成了以下配置:

System.config({
  packages: {
    'base/src': {
      defaultExtension: false,
      format: 'register',
      map: {
        './components/test.service': '/base/dist/components/test.service.js',
        (...)
      }
    }
  }
});

所以要调试您的问题,我会执行以下操作:

  • createPathRecords 函数中记录appPath

    reduce(function createPathRecords(pathsMapping, appPath) {
      console.log('appPath = '+appPath);
      (...)
    }
    
  • 记录整个map 配置:

    console.log(Object.keys(window.__karma__.files).filter(onlyAppFiles).reduce(createPathRecords, {}));
    

根据这些提示,您需要调整您的代码以具有此配置:

{
  './components/test.service': '/base/dist/components/test.service.js',
  (...)
}

【讨论】:

  • 我开始记录路径。首先:其中一个问题是我从来没有达到 createPathRecords() 因为我的代码在那之前的某个地方崩溃了。我添加了在 shim.js 中调用的其他方法。我用“dist”替换“src”仍然得到错误,但至少现在导入文件的路径是好的......
  • 我终于修好了!谢谢蒂埃里!问题(如您所想)是 karma.test.shim.js 中的某个地方是 src 而不是“dist”。对我来说那个地方在 onlyAppFiles() 中。不再有业力错误。
猜你喜欢
  • 1970-01-01
  • 2016-06-26
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 2017-06-12
  • 1970-01-01
相关资源
最近更新 更多