桶装进口似乎打破了装载顺序

Barrel Import Appears To Break Load Order

我有一个组件正在尝试进行单元测试,但我不断收到这些错误,具体取决于我的导入语句:

Error: Cannot resolve all parameters for 'MyComponent'(undefined, FormBuilder).

TypeError: Cannot read property 'toString' of undefined

我的组件有 2 个参数,一个是 FormBuilder,一个是必须注入的自定义服务:

import {MyService} from '../';

@Component({
    ...,
    providers: [MyService]
})
class MyComponent {
    constructor(service: MyService, fb: FormBuilder) { ... }
    ...
}

我的单元测试设置如下:

import {MyComponent} from './';
import {MyService} from '../';

describe('Component: MyComponent', () => {

    let builder: TestComponentBuilder;

    beforeEachProviders(() => [
        MyService,
        MyComponent
    ]);

    beforeEach(inject([TestComponentBuilder], function (tcb: TestComponentBuilder) {
        builder = tcb;
    }));

    it('should inject the component', inject([MyComponent],      
        (component: MyComponent) => {
            expect(component).toBeTruthy();
        })
    );

}

导入似乎是问题所在,因为我正在尝试使用桶:

|
|- my-component
|  |- index.ts
|  |- my.component.ts
|  |- my.component.spec.ts
|
|- my-service
|  |- index.ts
|  |- my.service.ts
|
|- index.ts

在我的 index.ts 文件中,我正在做:

export * from '<filename>';
export * from '<directory>';

视情况而定。

但是,当我将单元测试和组件中的导入更改为直接引用服务文件时,单元测试有效。

import {MyService} from '../my-service/my.service';

我在这个项目中使用 angular-cli,SystemJS 正在使用生成的配置文件进行配置:

...
const barrels: string[] = [
  ...,

  // App specific barrels.
  'app',
  'app/my-service',
  'app/my-component'
  /** @cli-barrel */
];

const cliSystemConfigPackages: any = {};
barrels.forEach((barrelName: string) => {
  cliSystemConfigPackages[barrelName] = { main: 'index' };
});

/** Type declaration for ambient System. */
declare var System: any;

// Apply the CLI SystemJS configuration.
System.config({
  map: {
    '@angular': 'vendor/@angular',
    'rxjs': 'vendor/rxjs',
    'main': 'main.js'
  },
  packages: cliSystemConfigPackages
});
...

当我从桶中导入时,组件和服务定义似乎没有在单元测试代码之前加载。应用程序本身将转译和 运行,无论哪种方式。

抱歉,如果这是一个广泛的问题,但我对 barrels 和 SystemJS 还是很陌生,我不知道如何进一步缩小范围:

这是 SystemJS/Jasmine/TypeScript/Angular2 的错误还是我的设置有误?

我必须查看您从中导入的桶中的内容才能确定,但​​听起来您需要更改桶中的导出顺序。

此处存在 angular2 存储库中的问题:https://github.com/angular/angular/issues/9334

If a component (A) imports and uses a service/component (B) from a barrel containing the exports of both A and B, and A appears before B in the barrel, the imported value of B is undefined.

所以在你的情况下,如果你将根 index.ts 修改为以下内容,你应该能够从你的桶中导入。

export * from my-service;
export * from my-component;