Karma - Jasmine无法在Ionic app

时间:2018-06-05 10:56:05

标签: angular typescript ionic-framework ionic3 karma-jasmine

我有一个使用多个环境文件的Ionic应用程序:

  • environment.dev.ts(dev)
  • environment.local.ts(local)
  • environment.ts(prod)

我使用path来解析配置,使用以下webpack.conf.js:

const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const useDefaultConfig = require('@ionic/app-scripts/config/webpack.config.js');

const env = process.env.MY_ENV || 'local';

useDefaultConfig.prod.resolve.alias = {
  "@app/env": path.resolve(environmentPath('prod'))
};

useDefaultConfig.dev.resolve.alias = {
  "@app/env": path.resolve(environmentPath('dev'))
};

if (env !== 'prod' && env !== 'dev') {
  // Default to dev config
  useDefaultConfig[env] = useDefaultConfig.dev;
  useDefaultConfig[env].resolve.alias = {
    "@app/env": path.resolve(environmentPath(env))
  };
}

function environmentPath(env) {
  const filePath = './src/environments/environment' + (env === 'prod' ? '' : '.' + env) + '.ts';
  if (!fs.existsSync(filePath)) {
    console.log(chalk.red('\n' + filePath + ' does not exist!'));
  } else {
    return filePath;
  }
}

module.exports = () => useDefaultConfig;

我有一个karma配置加载一个特定的tsconfig,它位于名为test-config的同一个文件夹中:

karmaTypescriptConfig: {
  tsconfig: "./tsconfig.spec.json"
},

我的tsconfig:

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2017"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5",
    "baseUrl": "./../",
    "paths": {
      "@app/env": [
        "src/environments/environment"
      ]
    }
  },
  "noUnusedLocals": true,
  "noUnusedParameters": true,
  "exclude": [
    "../node_modules",
    "src/**/*.spec.ts"
  ],
  "compileOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}

当我运行ionic serve并解决了路径并且一切正常时,我得到了相同的tsconfig。

但是当我运行业力来执行测试时,我遇到了以下错误:

  

找不到模块:错误:无法解析'@ app / env'

我不知道为什么,但似乎karma没有加载我的自定义tsconfig。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我最终在我的业力配置中添加以下行 - > webpack dedacated config:

resolve: {
    extensions: ['.ts', '.js'],
    alias: {
      '@app/env': path.resolve(__dirname, '../src/environments/environment.local.ts')
    }
  },