Angular 2 - component layout with injection

I'm trying to run some tests on a component that has a subcomponent in it:

this is the parent component template:

<header></header>
<snackbar></snackbar>

      

this snackbar component is the one that is causing me problems when trying to validate the parent component: the snackbar component has an injectionToken dependency which is used to pass the appConfig component (some constants) required by the component. The AppConfig is injected into the snackbar component like this:

import { APP_CONFIG, AppConfig } from '../../../../app.config';

export class SnackbarComponent implements OnInit {

  private config: MdSnackBarConfig;

  constructor(
    @Inject(APP_CONFIG) config: AppConfig
  ) {
    let snackBarConfig = new MdSnackBarConfig();
    this.config = snackBarConfig;
  }
}

      

the parent component tests well, but when trying to resolve the snackbar component dependency it fails as it cannot find a supplier for the injection dependency.

I guess the correct way to solve this problem would be to mock the snackbar component, sandly I havent found any way that works.

Any help would be greatly appreciated. Thanks to

+3


source to share


1 answer


I assume your app.config looks something like the Angular tutorial:

import { InjectionToken } from '@angular/core';

export interface IAppConfig {
  smartTable: {
    widthColumnNumber: string;
    widthColumnPercentage: string;
  };
}

export const APP_DI_CONFIG: IAppConfig = {
  smartTable: {
    widthColumnNumber: '5rem',
    widthColumnPercentage: '10rem',
  },
};

export let APP_CONFIG = new InjectionToken<IAppConfig>('app.config');

      

To add a provider for this, you must add a provider to the NgModule like this:



import { APP_CONFIG, APP_DI_CONFIG } from '../../app.config';

...
...

{ provide: APP_CONFIG, useValue: APP_DI_CONFIG },

      

And in your unit test, you can do this to mock the config:

import { APP_CONFIG } from '../../app.config';

...
let mockConfig = {};
...

{ provide: APP_CONFIG, useValue: mockConfig },

      

0


source







All Articles