karma-typescript找不到模块

时间:2017-04-01 20:06:19

标签: javascript typescript karma-runner

我有一个非常小的项目,我正在尝试为其设置单元测试。项目在直接使用tsc 时编译正常,但是,在尝试执行使用karma-typescript框架的测试时,我收到以下的Typescript编译错误:

错误:

  

错误[compiler.karma-typescript]:src / drawing / canvas.model.ts(1,23):   错误TS2307:找不到模块' utils'。

     

错误[compiler.karma-typescript]:src / models / grid.model.ts(1,23):错误TS2307:找不到模块' utils'。

     

错误[compiler.karma-typescript]:src / utils / specs / obj.utils.spec.ts(1,23):错误TS2307:找不到   模块' utils'。

项目结构: 我有一个项目设置,其结构如下:

|-dist/
|-node_modules/
|-src/
| |
| |-drawing/
| | |
| | |-canvas.model.ts
| |    ________________________________
| |   | import { Utils } from 'utils'; |  Karma Fails (tsc is fine)
| |    --------------------------------
| |
| |-models/
| | |
| | |-grid.model.ts
| |    ________________________________
| |   | import { Utils } from 'utils'; |  Karma Fails (tsc is fine)
| |    --------------------------------
| | 
| |-utils/
| | |
| | |-index.ts
| | |  _________________________
| | | | export module Utils {}  |
| | |  -------------------------
| | |
| | |-specs/
| | | |
| | | |-obj.utils.spec.ts
| | |    ________________________________
| | |   | import { Utils } from 'utils'; |  Karma Fails (tsc is fine)
| | |    --------------------------------
| | |
|-karma.config.js
|-tsconfig.json
|-package.json

我很清楚,我的tsconfig.json文件与内部用于karma-typescript的编译器设置之间存在差异。这是我如何组织这两个文件。根据{{​​3}},我可以在karma.conf文件中配置几个选项,告诉karma-typescript在我的Typescript配置文件中遵守我的设置,即"paths"属性,这是我为Typescript指定在哪里寻找我的utils模块。

KARMA.CONF.JS



// Karma configuration
// Generated on Fri Mar 31 2017 16:42:11 GMT-0700 (PDT)
module.exports = function(config) {
  config.set({
    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',
    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'karma-typescript'],
    // Plugins
    plugins: [
      'karma-spec-reporter',
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-jasmine-html-reporter',
      'karma-typescript'
    ],
    // list of files / patterns to load in the browser
    files: [{
      pattern: "./src/**/*.ts"
    }],
    // list of files to exclude
    exclude: ['**/*.spec.js'],

    // Karma Typescript compiler options
    karmaTypescriptConfig: {
      bundlerOptions: {
        resolve: {
          directories: ["src", "node_modules", "src/utils"]
        }
      }
    },
    compilerOptions: {
      module: 'commonjs',
      moduleResolution: 'node',
      paths: {
        'utils': ['./src/utils'], 'utils/*': ['./src/utils/*']
      }
    },
    tsconfig: './tsconfig.json',


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      "**/*.ts": ["karma-typescript"]
    },
    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'kjhtml', 'spec', "karma-typescript"],
    // 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: ['Chrome'],
    // 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
  })
}




这是我的Typescript配置文件。请注意,我在tsconfig文件的"utils"部分中注册"paths",这有助于Typescript编译器documentation for karma-typescript。这适用于普通的Typescript编译,但这可能是因为我的Typescript编译器实际上是尊重我的tsconfig文件中的设置。我正在使用 Typescript 2.0.10 。但似乎karma-typescript正在使用 Typescript 2.2.2 ,这可能是错误的潜在来源。我必须针对该版本运行我的编译器,看看我是否可以生成相同的错误。

TSCONFIG.JSON



{
  "compileOnSave": true,
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "./dist",
    "paths": {
      "utils/*": ["./src/utils/*"],
      "utils": ["./src/utils"]
    },
    "declaration": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es5", "dom"],
    "mapRoot": "./",
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5",
    "rootDirs": ["./dist", "."]
  },
  "exclude": ["./node_modules", "./dist", "**/*.d.ts"],
  "include": ["./src/**/*.ts"]
}




任何人都可以帮我解决这个问题吗?我对打字稿很体面,但对于Karma来说却很新鲜。我正在搜索文档大约2天,现在试图让这些简单的单元测试运行,但无济于事。不是因为我至少有了自己的路径。任何帮助将不胜感激!

更新 我尝试将我的本地安装的Typescript更新为 2.2.2 ,以匹配Karma-Typescript的版本 2.2.2 。同样的错误,相同的场景 - 我的本地版本编译得很好,但是Karma-Typescript版本很好。

2 个答案:

答案 0 :(得分:9)

Karma配置中存在一个小错误,compilerOptionstsconfig属性应位于karmaTypescriptConfig属性中。

根据您的项目结构示例,这里是tsckarma-typescript的最小工作配置示例:

<强> Karma.conf.js

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

        frameworks: ["jasmine", "karma-typescript"],

        files: [
            { pattern: "src/**/*.ts" }
        ],

        karmaTypescriptConfig: {
            compilerOptions: {
                module: "commonjs"
            },
            tsconfig: "./tsconfig.json",
        },

        preprocessors: {
            "**/*.ts": ["karma-typescript"]
        },

        reporters: ["progress", "kjhtml", "spec", "karma-typescript"],

        browsers: ["Chrome"]
    });
};

<强> tsconfig.json

{
    "compileOnSave": true,
    "compilerOptions": {
        "baseUrl": ".",
        "outDir": "./dist",
        "paths": {
            "utils/*": ["./src/utils/*"],
            "utils": ["./src/utils"]
        },
        "module": "es6",
        "moduleResolution": "node",
        "sourceMap": true,
        "target": "es5"
    }
}

我使用typescript@2.2.2karma-typescript@3.0.0对此进行了测试。

另外,请注意karma-typescript只有Typescript作为dev依赖项,让你使用1.6.2及更高版本的任何Typescript版本:)

答案 1 :(得分:2)

由于Error: Unable to resolve module [...] from [...]中的自定义模块路径,我出现了一个错误tsconfig.json。这是我针对该问题的解决方案:

// tsconfig.json
"compilerOptions" {
    ...
    "paths": { // My custom module path
        "parchment/blot/*": ["node_modules/parchment/dist/src/blot/*"],
        "parchment/attributor/*": ["node_modules/parchment/dist/src/attributor/*"]
    },
    ...


// karma.conf.js
...
karmaTypescriptConfig: {
    tsconfig: './tsconfig.json',
    bundlerOptions: {
        resolve: {
            alias: {
                'parchment/dist/src/attributor': './node_modules/parchment/dist/parchment.js',
                'parchment/dist/src/blot/abstract': './node_modules/parchment/dist/parchment.js'
            },
            extensions: ['.js] // Extension that causes the error
        }
    }
}
...

如您所见,bundlerOptions.resolve是解决方案的关键。