Angular 2使用webpack测试业力无法找到变量:Map

时间:2016-10-19 17:37:35

标签: javascript testing angular webpack karma-jasmine

我试图用karma和webpack来测试我的指令。 这是业力配置文件

module.exports = function (config) {
    config.set({
        basePath: './',
        frameworks: ["jasmine"],
        files: [
            {
            pattern: 'directive.spec.ts',
            watched: false
        }],
        exclude: [],
        preprocessors: {
            'directive.spec.ts': ['webpack', 'sourcemap']
        },
        webpackServer: {
            noInfo: true
        },
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: [
            "PhantomJS"
        ],
        singleRun: true,
        reporters: ['mocha'],
        webpack: {
            resolve: {
                extensions: ['', '.ts', '.js'],
                modulesDirectories: ['node_modules', '.'],
            },
            module: {
                loaders: [{
                    test: /\.ts$/,
                    loader: 'awesome-typescript-loader'
                }]
            },
            stats: {
                colors: true,
                reasons: true
            },
            debug: true,
            devtool: 'inline-source-map'
        }
    });
};

并指示.spec.ts:

import { MyDirective } from './directive';
import {TestComponent} from './test';
import {
  async,
  inject,
  TestBed,
} from '@angular/core/testing';

describe('TestComponent', () => {

  let fixture: any;

beforeEach(() => {
  fixture = TestBed.configureTestingModule({
    declarations: [ TestComponent, MyDirective]
  })
  .createComponent(TestComponent);
  fixture.detectChanges();
});

  it('should work', () => {
    expect(true).toBe(true);
  });

但是当我尝试运行测试时,我收到了这个错误:

  

PhantomJS 2.1.1(Mac OS X 0.0.0)错误ReferenceError:无法找到   变量:在directive.spec.ts上映射:1380

我在这里缺少什么?

2 个答案:

答案 0 :(得分:0)

请按照以下步骤操作。它对我有用:

1)使用以下代码创建“karma-main.js”文件

require('core-js/es6');
require('core-js/es7/reflect');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy');
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');

var appContext = require.context('<Source code root folder>', true, /\.spec\.ts/); // Assuming test case files ends with spec.ts

appContext.keys().forEach(appContext);

var testing = require('@angular/core/testing');
var browser = require('@angular/platform-browser-dynamic/testing');

testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting());

2)你的karma.conf.js文件看起来应该是

var webpackConfig = require('./webpack.config')

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

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    plugins: [
      'karma-jasmine',
      'karma-PhantomJS-launcher',
      'karma-webpack'
    ],

    webpack: webpackConfig,

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      { pattern: '<relative path to karma-main.js>', watched: false }
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      '<relative path to karma-main.js>': ['webpack']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}

答案 1 :(得分:-1)

这是我的猜测:代码中的某处使用了ES6中出现的类attributedText。但PhantomJS并不知道这个课程,因为它太新了。

所以有3种选择:

  • 摆脱var highlightedText = NSMutableAttributedString(string: "this text is highlighted") let highlightedRange = NSRange(location: 0, length: highlightedText.characters.count) highlightedText.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellow, range: highlightedRange) attributedText.replaceCharacters(in: highlightedRange, with: highlightedText) 的使用,只使用当前的JS功能(如对象属性) - 最干净的方法。
  • 使用transpiler将您的ES6代码转换为现代浏览器所熟知的ES5。这有很大的缺点,因为它会弄乱您的行号,您可能不得不牺牲调试某些代码的可能性。
  • 使用实现ES6功能的polyfill作为外部库中的函数(如Sachin Gaur suggested