Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 - mock component with injectionToken dependency

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.

like image 664
Albert Prats Avatar asked Jul 03 '17 07:07

Albert Prats


1 Answers

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 },
like image 187
Tonio Avatar answered Sep 30 '22 16:09

Tonio