When attempting to unit test my component, I keep encountering errors related to my import statements:
Error: Cannot resolve all parameters for 'MyComponent'(undefined, FormBuilder).
TypeError: Cannot read property 'toString' of undefined
The component in question requires two injected parameters - FormBuilder and a custom service:
import {MyService} from '../';
@Component({
...,
providers: [MyService]
})
class MyComponent {
constructor(service: MyService, fb: FormBuilder) { ... }
...
}
Here is how my unit test is structured:
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 successfully inject the component', inject([MyComponent],
(component: MyComponent) => {
expect(component).toBeTruthy();
})
);
}
The issue seems to stem from my use of barrels in the imports:
|
|- my-component
| |- index.ts
| |- my.component.ts
| |- my.component.spec.ts
|
|- my-service
| |- index.ts
| |- my.service.ts
|
|- index.ts
In my index.ts files, I'm exporting like this:
export * from '<filename>';
export * from '<directory>';
However, changing the imports in both the unit test and component to directly reference the service file resolves the issues:
import {MyService} from '../my-service/my.service';
I am using angular-cli in this project and SystemJS with configurations defined by the generated config file:
...
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
});
...
It appears that importing from the barrels prevents the proper loading of component and service definitions before the unit test code runs.
As someone new to barrels and SystemJS, I'm unsure if this is a bug with the technologies or an error in my setup. Any guidance on narrowing down the issue would be appreciated.