I'm trying to do some tests in 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 giving me problems when I try to test the parent component: "snackbar" component has a dependency with injectionToken, that is used to pass to the component the appConfig (some constants) that the component requires. 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 good, but when tries to resolve the "snackbar" component dependency it fails since its not able to find the provider for the injectionToken dependency.
I guess that a proper way to solve this issue would be to mock the "snackbar" component, sadly I haven't found any way that works.
I guess your app.config looks something like this as described in 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');
In order to add a provider for this, you should add a provider in 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 in order to mock the config:
import { APP_CONFIG } from '../../app.config';
...
let mockConfig = {};
...
{ provide: APP_CONFIG, useValue: mockConfig },
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With