Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular APP_INITIALIZER to load config file in tests

Tags:

angular

I'm using this gist to read configuration file during application startup. This works fine but when doing unit tests I get error Cannot read property 'SomeProperty' of null.

I have added the provider to test as well

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports: [ReactiveFormsModule, RouterTestingModule, HttpModule],
      providers: [AuthService,
        SettingsService,
        AppConfig,
        {
            provide: APP_INITIALIZER,
            useFactory: initConfig,
            deps: [AppConfig],
            multi: true
        },
        ]
    })
    .compileComponents();
  }));

Any pointers to resolve this?. Thanks in advance.

like image 529
Yogendra Avatar asked May 08 '17 07:05

Yogendra


2 Answers

looks like there is an issue with how Angular treats the APP_INITIALIZER while running tests (see https://github.com/angular/angular/issues/24218).

The workaround for now is to call this before in each: test

  beforeEach(async () => {
    // until https://github.com/angular/angular/issues/24218 is fixed
    await TestBed.inject(ApplicationInitStatus).donePromise;
  });

for angular <9, use TestBed.get(...) instead.

like image 187
RocketMan Avatar answered Oct 14 '22 00:10

RocketMan


I spun my wheels on something like this for a while. In the end I just provided a mock of the service in the "deps" of the APP_INITIALIZER provider and made sure it didn't do anything in the unit tests.

Then you just test the initializer and service independently and I think that's the best you can do.

like image 32
jakefreeberg Avatar answered Oct 13 '22 23:10

jakefreeberg