【问题标题】:Barrel Import Appears To Break Load Order桶装进口似乎打破装载顺序
【发布时间】:2016-09-20 19:07:16
【问题描述】:

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

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
});
...

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

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

这是 SystemJS/Jasmine/TypeScript/Angular2 的错误还是我在设置中做错了什么?

【问题讨论】:

    标签: typescript angular jasmine systemjs


    【解决方案1】:

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

    angular2 repo 中存在问题:https://github.com/angular/angular/issues/9334

    如果组件 (A) 从 包含 A 和 B 的出口的桶,并且 A 出现在 B 之前 在桶中,B的导入值是未定义的。

    因此,在您的情况下,如果您将根 index.ts 修改为以下内容,您应该可以从您的桶中导入。

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

    【讨论】:

    • 听起来和我看到的完全一样,谢谢。希望它很快就会得到修复。
    • 我正在使用 angular2-seed 项目,只花了 2 个小时 + 试图弄清楚为什么我的服务没有在我的组件构造函数中被解析为提供者......该死的服务在桶 index.ts 中的组件之后声明。这很难发现!
    猜你喜欢
    • 1970-01-01
    • 2020-03-18
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多