11

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.

2
  • Can you share more code? I don't see SomeProperty Commented May 8, 2017 at 8:47
  • Have you figured out the solution? Commented Sep 11, 2017 at 14:41

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried it and it works great, but I wanted to know if this solution makes the test engine to wait until all APP_INITIALIZER promises are fulfilled. It should me marked as the correct answer, imho.
Hi Ramiro, yes I believe you are correct. My understanding is that this async/await pattern makes each test execution wait until the APP_INITIALIZER promise is fulfilled. Hope that helps!
1

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.

Comments

0

I think to separate test is a good idea. So, I mocked the config into my test and worked. Of course, I had to create another spec to ConfigService.

describe('My unit test', () => {
  
  const mock= { get myConfig() { return { url: 'http://mock' }; } };
  ...

  beforeEach(async () => {

    TestBed.configureTestingModule({
      imports: [...],
      declarations: [...],
      providers: [
        { provide: ConfigService, useValue: mock}
      ]
    }).compileComponents();
      ...
  });

...
});

1 Comment

your reference link is dead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.