mardi 25 juin 2019

Angular 7 testing with injection tokens

Using: Angular 7 Jasmine 2.8.0 Jasmine Core 2.99.1

My unit test is testing a component using an Injection Token, and breaks.

It is failing with the error Uncaught TypeError: Cannot read property 'app' of undefined thrown

The only reference in the code to app without a suffix is in the configuration file. If I remove the bit with the configuration file from the component the test runs fine. If I Inject the config but don't use it, the test runs fine. Only thing that breaks it is if I use the configuration in the component.

The component I am testing uses some configuration through an Injection Token.

This is my test:

describe('AppSomethingComponent', () => {
    let component: AppSomethingComponent;
    let fixture: ComponentFixture<AppSomethingComponent>;
    const mockDataConfig: IDataConfig = {
        ...
        baseLayers: {
            cartodb_black_sea: {
                ...
                url: ''
            }
        }
    };
    const mockAppConfig: IAppConfig = {
      defaultBaseLayerKey: 'cartodb_black_sea',
      ...
  };

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [AppSomethingComponent],
            providers: [
                {
                    provide: APP_CONFIG,
                    useValue: mockAppConfig
                },
                {
                  provide: DATA_CONFIG,
                  useValue: mockDataConfig
                }
            ]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(AppSomethingComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
      expect(component).toBeTruthy();
    });
});



This is my component:

export class AppSomethingComponent implements OnInit {
    private map: L.Map;
    constructor(
        @Inject(DATA_CONFIG) public dataConfig: IDataConfig,
        @Inject(APP_CONFIG) public appConfig: IAppConfig,
    ) {
        // linter go away
    }

    public ngOnInit() {
        this.map = L.map('app-map').setView([20, 20], 2);

// This is where I think it is breaking in the test
        L.tileLayer(
            this.dataConfig.baseLayers[this.appConfig.defaultBaseLayerKey].url
        ).addTo(this.map);
    }
}

This is my config

export const APP_DI_CONFIG: IAppConfig = {
    defaultBaseLayerKey: ''
};

export let APP_LOCAL_CONFIG: IADT2Config = (window as any).__appConfig;
export const APP_CONFIG = new InjectionToken<IAppConfig>('app.config');


My guess is the tests are looking for app.config from new InjectionToken<IAppConfig>('app.config');, not finding it, and freaking out. I had to replace some words so forgive me if capitalization is not consistent, it is in the actual app and in my actual tests.

Aucun commentaire:

Enregistrer un commentaire