首页 文章

桶进口似乎打破了加载订单

提问于
浏览
2

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

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>';

作为适当的 .

但是,当我更改单元测试AND组件中的导入以直接引用服务文件时,单元测试工作 .

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的错误还是我在设置中做错了什么?

1 回答

  • 3

    我必须看到你要导入的桶的内容才能确定,但听起来你需要更改桶内出口的顺序 .

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

    如果组件(A)从包含A和B的导出的桶中导入并使用服务/组件(B),并且A出现在桶中的B之前,则导入的B值未定义 .

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

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

相关问题