Karma,Typescript定义文件未加载

时间:2017-08-26 13:06:05

标签: typescript webpack karma-runner tsconfig

我正在使用karma,webpack和typescript设置开发环境,但我遇到的问题是karma没有在测试中应用自定义定义文件。

这是我的项目文件结构:

// file structure
project/
    config/
        karma.conf.js
    tests/
        test-files.ts 
        ...        
    src/
        tsdefinitions.d.ts
        other-ts-files.ts
        ...
    tsconfig.json

这里是与webpack和typescript相关的karma配置部分

webpack: {
  devtool: 'eval-source-map',
  resolve: {
    extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js']
  },
  module: {
    loaders: [{
      test: /\.tsx?$/,
      loader: 'awesome-typescript-loader'
    }]
  }
},
webpackMiddleware: {stats: 'errors-only'},
mime: {'text/x-typescript': ['ts','tsx']},
basePath: '../',
files: [{
  pattern: './test/**/*.ts',
  watched: false
}],
preprocessors: {
  './test/**/*.ts': ['webpack', 'sourcemap']
}

最后是tsconfig.json

{
  "compilerOptions": {
    "removeComments": true,
    "allowSyntheticDefaultImports": true,
    "baseUrl": "./",
    "sourceMap": true,
    "noImplicitAny": true,
    "allowJs": true,
    "module": "commonjs",
    "target": "es2015",
    "paths": {
      "jquery": ["node_modules/jquery/dist/jquery"]
    },
    "exclude": ["node_modules"],
    "files": [
      "src/**/*.ts"
    ]
  },
  "awesomeTypescriptLoaderOptions": {
    "useCache": false,
    "useBabel": true,
    "babelOptions": {
      "presets": [
        "es2015",
        "stage-0"
      ]
    }
  }
}

我正在进行像这样的业力测试

./node_modules/.bin/karma start ./config/karma.conf.js

现在当我使用karma构建项目文件时,一切正常,它们构建没有错误。

但是当我运行测试构建时,在tsdefinitions.d.ts文件中声明了很多缺少Window接口属性的错误。

1 个答案:

答案 0 :(得分:0)

通过将我的类型放在与源文件不同的文件夹中,并使用tsconfig.json字段将其包括在typeRoots中,我能够实现这一点。

我的tsconfig.json

{
  "compilerOptions": {
    ...
    "typeRoots": [
      "./@types"
    ]
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "src/**/*.test.ts"
  ]
}

karma.config.js:

const webpackConfig = require("./webpack.test");

module.exports = function(config) {
  config.set({
    basePath: "",
    frameworks: ["mocha", "chai"],
    plugins: [
      "karma-chai",
      "karma-chrome-launcher",
      "karma-mocha",
      "karma-mocha-reporter",
      "karma-sourcemap-loader",
      "karma-webpack"
    ],
    files: [
      "src/**/*.test.ts"
    ],
    exclude: [],
    webpack: webpackConfig,
    preprocessors: {
      "**/*.ts": ["webpack", "sourcemap"]
    },
    mime: { "text/x-typescript": ["ts", "tsx"] },
   ...
  });
};

现在,我可以为没有任何类型的模块定义类型,如下所示:
@types/universal-url/index.d.ts

declare module 'universal-url' {
  export {URL, URLSearchParams} from 'whatwg-url' 

  export function shim(): void
}

还有我的src/utils/parseUrl.ts文件:

import { URL } from 'universal-url'

export function parseUrl(url: string) {
  return new URL(url)
}

同样,密钥是tsconfig.json的typeRoots字段。这是文档:https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types