简体   繁体   中英

Karma cannot find angular2 “barrel” import

We've got an Angular2 project using the barrel import pattern. I'm attempting to write unit tests for it, however Karma cannot seem to find the modules that are referenced by the barrel statements.

The file being tested imports using:

import {provider1, provider2, provider3} from "../../../core/providers";
import {component1} from "../../controls";

And karma outputs the following warnings:

13 05 2016 08:57:43.732:WARN [web-server]: 404: /base/src/app/core/providers
13 05 2016 08:57:43.732:WARN [web-server]: 404: /base/src/app/core/controls

Now the section of the karma config file that loads our client scripts:

// paths loaded via module imports
{ pattern: "src/app/**/*.js", included: false, watched: true },
// paths to support debugging with source maps in dev tools
{ pattern: "src/app/**/*.ts", included: false, watched: false },

This should load all the client scripts, but I think that since the file I am unit testing uses a barrel import, Karma doesn't know what to do with it. Neither do I...

I have attempted to add a proxy for this barrel pattern, but that did not work.

What should I be doing?

Turns out that using SystemJS with Angular2, you need to give the SystemJS config file information about what a "barrel" means or TypeScript will have no idea what to look for when it's compiling your project. Meaning, when you say:

import {component1} from "../../controls";

TypeScript will look for "../../controls.js" by default, unless you tell it not to. In my main config file I had specified some mappings for these for SystemJS to know what to look for in these buckets as so:

packages: {
  "src/path/path/controls": {
    "main": "index"
  },
  "src/path/path/providers": {
    "main": "index"
  }
},

However, I also needed to add this to the karma-test-shim.js file so Karma would know what to look for.

After adding this to my karma-test-shim.js file, it worked fine.

var packages = {
    "base/src/path/path/controls": {
        "main": "index"
    },
    "base/src/path/path/providers": {
        "main": "index"
    }
};
System.config(packages);

is the line ending

...watched:

truncated? missing true/false},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM