Load Order Possibly Disrupted by Arrival of Barrel Imports

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.

Answer №1

To determine the actual issue, it is necessary to inspect the contents of the barrels that are being imported. It seems like there may be a need to adjust the order of exports within the barrel.

There is a known problem in the angular2 repository outlined here: https://github.com/angular/angular/issues/9334

The issue arises when a component (A) imports and utilizes a service/component (B) from a barrel that contains both A and B. If A precedes B in the barrel, then the imported value of B will be undefined.

In this scenario, updating your root index.ts as shown below should allow you to successfully import from your barrels:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to Dockerize an Angular CLI app, nothing seemed to happen

I attempted to dockerize my Angular application and created a Dockerfile as follows: FROM teracy/angular-cli as angular-built WORKDIR /usr/src/app COPY package.json package.json RUN npm install COPY . . RUN ng build FROM nginx:alpine LABEL author="pleijan ...

How can I incorporate an interface and specify a particular type as the return value in TypeScript?

interface Inter{ str:string } function func(){ let v:Inter={ str:'abc' }; return v; } func()//Is there a way to ensure that the type of value returned from `func` is {str:'abc'} without explicitly declaring it i ...

Leveraging es6-promise in conjunction with TypeScript 2.1 and ES5 Webpack for streamlined async/await functionality

Utilizing es6-promise with TypeScript version 2.1.1 that targets ES5 and webpack in my project has presented some challenges. app.ts import "es6-promise/auto"; export class Foo { bar() : Promise<string>{ return Promise.resolve("baz"); ...

The favicon refuses to load

Image 'http://localhost:8000/favicon.ico' could not be loaded as it contravened the Content Security Policy directive "default-src 'none'". It is important to note that since 'img-src' was not specifically defined, 'defau ...

ngFor filter based on user input

I am working on a 2-step stepper feature where I need to filter the values in my amountArray based on the age of the person. If the person is above 50 years old, display only the values 10000 and 15000. For Euro currency, show values 25000 and 50000. I att ...

Refresh the content of an Angular modal with updated data each time the modal is launched

Currently, I am working on an angular web project that involves a main component class loading a Modal to update a report. Within this Modal, there are tabs - one of which is the transaction tab for which I am responsible. However, I have encountered an is ...

Encountering error TS2307 while using gulp-typescript with requirejs and configuring multiple path aliases and packages

Currently, I am working on a substantial project that heavily relies on JavaScript. To enhance its functionality, I am considering incorporating TypeScript into the codebase. While things are running smoothly for the most part, I have encountered an issue ...

No errors are being displayed with the React Hook Form using Zod and Material UI

Presenting my custom ProductInfoForm built using Material UI, react-hook-form with zod validations. However, I am encountering an issue: upon submitting the form, the data is displayed in the console as expected, but when intentionally triggering an error, ...

The error message "Property 'map' is not found on type 'User' in React with typescript"

I am currently experimenting with React using TypeScript. I have set up useState with an object but I am encountering issues trying to use the map function with that object. Below is the error message I am facing: Property 'map' does not exist ...

Angular generates a dynamic interface to fetch data from Wordpress REST API posts (special characters in property names are causing issues)

I've been developing a front-end Angular application that interacts with the Wordpress REST API to fetch and display post data. My goal is to create an interface to handle the responses and render the posts in the template. However, I encountered an ...

Should Jasmine recommend decreasing the number of local variables or focusing on improving karma coverage reports?

My Karma coverage report indicates that the local variable is not being covered. Is this a possible issue with the karma-coverage report? Please take a look at the Angular Controller Code below. 'use strict'; angular.module('moduleName&ap ...

Connecting the mat-progress bar to a specific project ID in a mat-table

In my Job Execution screen, there is a list of Jobs along with their status displayed. I am looking to implement an Indeterminate mat-progress bar that will be visible when a Job is executing, and it should disappear once the job status changes to stop or ...

Error in refreshing the deployment package of angular 4 on an Apache server

At the moment, my Angular application runs on an Apache server at the 'http://localhost' root or index page. However, when I refresh the inner page 'http://localhost/dms-data/summary-of-findings', the browser displays Page Not Found T ...

What is the reason behind line-height not affecting the clickable area when reduced?

I have been working on a personal project where I added thumbnails for images that can be scrolled through and clicked to set the main image. However, I encountered a strange issue. To demonstrate the problem, I created a Stackblitz project here: https:// ...

Can you explain the distinction between needing ts-node and ts-node/register?

Currently, I am conducting end-to-end tests for an Angular application using Protractor and TypeScript. As I was setting up the environment, I came across the requirement to include: require("ts-node/register") Given my limited experience with Node.js, I ...

How can I pass properties from a childComponent to a parent component in Angular 2 without prior knowledge of the childComponent's class?

My main goal is to accomplish the following : I currently have a component setup like this: import { Component, Output, EventEmitter, OnInit } from '@angular/core'; @Component({ selector: 'like', template: '<p>this is ...

Angular 2 - Can a Content Management System Automate Single Page Application Routing?

I am interested in creating a single-page application with an integrated content management system that allows users to edit all aspects of the site and add new pages. However, I have found it challenging to configure the SPA to automatically route to a n ...

Angular 15 is unfortunately not compatible with my current data consumption capabilities

I'm currently facing an issue with Angular 15 where I am trying to access the "content" element within a JSON data. However, when attempting to retrieve the variable content, I am unable to view the elements it contains. import { Component, OnInit } ...

Using Angular 2, how to filter a single column based on multiple values?

If I have an array of objects as shown below [ {name: 'aaa', type: 'A'}, {name: 'bbb', type: 'B'}, {name: 'ccc', type: 'A'} .... ] I want to build a filter in Angular that displays ...

Understanding how to deduce parameter types in TypeScript

How can I infer the parameter type? I am working on creating a state management library that is similar to Redux, but I am having trouble defining types for it. Here is the prototype: interface IModel<S, A> { state: S action: IActions<S, A&g ...