Search code examples
angulartypescriptionic-frameworkionic3karma-jasmine

Karma - Jasmine could not resolve typescript path in Ionic app


I have a Ionic app that uses multiple environment files:

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

I used path to resolve the config with the following 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;

I have a karma config that load a specific tsconfig which is in the same folder named test-config:

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

My 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
  }
}

I've got the same tsconfig when I run ionic serve and got the path resolved and everything works.

But when I run karma to execute the tests I've got the following error:

Module not found: Error: Can't resolve '@app/env'

I don't know why, but it seems like karma doesn't load my custom tsconfig.

Thank you for your help.


Solution

  • I finaly add the following lines in my karma configuration -> webpack dedacated config :

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