简单的因果报应+;Typescript配置-引用错误:未定义x

简单的因果报应+;Typescript配置-引用错误:未定义x,typescript,karma-runner,Typescript,Karma Runner,我想使用Karma设置一个基本的测试运行程序来测试Typescript类 当我运行测试karma start时,我得到了错误ReferenceError:Calculator未定义。推测,karma runner可能没有导入传输的源或预处理器没有传输源 我的来源是下面的revant部分。如何使配置工作/我缺少什么 我目前的理解是transpiler和karma“files”配置属性将为我加载calculator类。 transpiler => lib/calculator.ts => lib/c

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

当我运行测试
karma start
时,我得到了错误
ReferenceError:Calculator未定义。
推测,karma runner可能没有导入传输的源或预处理器没有传输源

我的来源是下面的revant部分。如何使配置工作/我缺少什么

我目前的理解是transpiler和karma“files”配置属性将为我加载calculator类。 transpiler => lib/calculator.ts => lib/calculator.ts files => okay, loading lib/**/.js /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');
    }
 }
 ...

因为您将计算器定义为

export class Calculator{...}
这意味着您的
/lib/calculator.ts
是一个模块,它的类需要由其他模块导入才能可见(它们不是全局的)

因此,您的
/test/calculator.test.js
需要以某种方式导入此模块。如何做到这一点取决于
tsconfig.json中的模块配置

在您的情况下,您可能希望使用
“模块”:“commonjs”
“模块”:“amd”

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

您的另一个选择是不“导出”您的
计算器
类。这将使它在全球范围内可用。但是,您确实应该尝试使用模块方式,因为在更大的应用程序中,这是推荐的方法

export class Calculator{...}