简单的Karma + Typescript配置 - 参考错误:未定义x

时间:2016-10-30 12:39:46

标签: typescript karma-runner

我想使用Karma设置一个基本的测试运行器来测试Typescript类。

当我运行测试karma start时,我收到错误ReferenceError: Calculator is not defined.据推测,业力运行器可能不会导入已转换的源或预处理器不会传输源。

我的来源为here in a repo,其中包含以下部分。如何让配置工作/我缺少什么?

我目前的理解是,转发器和业力'文件'配置属性将为我加载计算器类。

transpiler => lib/calculator.ts => lib/calculator.ts
files => okay, loading lib/**/.js

/lib/calclulator.ts

export class Calculator{
  add ( a : number , b : number) : number {
    return a + b;
  } 
}

/test/calculator.test.js

describe('Demo Test Runner', function() {
  var calc = new Calculator();
  it('should return 3 for 1 + 2', function() {
   expect( calc.add(1,2) ).toBe(3);
  });
});

的package.json

...
"devDependencies": {
  "jasmine-core": "^2.5.2",
  "karma": "^1.3.0",
  "karma-chrome-launcher": "^2.0.0",
  "karma-jasmine": "^1.0.2",
  "karma-typescript-preprocessor": "^0.3.0"
}

karma.conf.js

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

 ...
 frameworks: ['jasmine'],

 files: [
    'lib/**/*.js',
    'test/**/*.js'
  ],


 preprocessors: {
   '**/*.ts': ['typescript']         
 },


 typescriptPreprocessor: {
    // options passed to the typescript compiler 
    options: {
      sourceMap: true, // (optional) Generates corresponding .map file. 
      target: 'ES5', // (optional) Specify ECMAScript target version: 'ES3' (default), or 'ES5' 
      module: 'amd', // (optional) Specify module code generation: 'commonjs' or 'amd' 
      noImplicitAny: true, // (optional) Warn on expressions and declarations with an implied 'any' type. 
      noResolve: true, // (optional) Skip resolution and preprocessing. 
      removeComments: true, // (optional) Do not emit comments to output. 
      concatenateOutput: false // (optional) Concatenate and emit output to single file. By default true if module option is omited, otherwise false. 
    },
    // transforming the filenames 
    transformPath: function(path) {
      return path.replace(/\.ts$/, '.js');
    }
 }
 ...

1 个答案:

答案 0 :(得分:0)

因为您将计算器定义为

export class Calculator{...}

这意味着您的/lib/calculator.ts是一个模块,它的类需要由其他模块导入才能看到它们(它们不是全局的)。

所以你的/test/calculator.test.js需要以某种方式导入这个模块。如何执行此操作取决于tsconfig.json

中的模块配置

在您的情况下,您可能希望使用"module" : "commonjs""module": "amd"

但是,您需要一个额外的插件才能加载这些模块。如果您使用amd,那么karma-requirejs之类的内容,如果您使用commonjs,则可能需要karma-webpack之类的内容。然后,您需要使用必要的语法将其导入js文件(例如var MyCalculator = require('/lib/calculator');

你的另一个选择是不要出口"你的Calculator课程。这将使其全球可用。但是,您应该尝试让模块工作,因为这是大型应用程序中的推荐方法。

相关问题