0

I'm using AngularFire2. I got this exception when running tests.

This is what my test looks like:

import {inject, TestBed} from '@angular/core/testing';
import {FIREBASE_PROVIDERS, defaultFirebase, AngularFire} from 'angularfire2';

describe('stock data service', () => {
    beforeAll(() => {
        const config = {
            apiKey: "123",
            authDomain: "123.firebaseapp.com",
            databaseURL: "https://123.firebaseio.com",
            storageBucket: "123.appspot.com",
        }; 
        TestBed.configureTestingModule({
            providers: [FIREBASE_PROVIDERS, defaultFirebase(config)]   
        });
    });

    it('should connect to Firebase', inject([AngularFire], (af : AngularFire) => {
        expect(af.database).not.toBe(null);
    }));

});

I guess that AngularFire cannot be injected because it is a function?

user73554
  • 93
  • 1
  • 9

1 Answers1

1

Replacing 'beforeAll' with 'beforeEach' solves the issue.

But can someone explain why this change made it work?

Here's what I've found:

I can see that the extra providers get added to the global TestBed after configureTestingModuleis called. However, with beforeAll, these extra providers somehow get lost when TestBed.execute(tokens: any[], fn: Function) is called later, and therefore fail to be found by dependency injector.

user73554
  • 93
  • 1
  • 9
  • 2
    Angular [configures a `beforeEach` call](https://github.com/angular/angular/blob/2.0.0/modules/%40angular/core/testing/testing.ts#L23-L28) that resets the `TestBed`. That's why the `TestBed.configureTestingModule` call needs to be made in a `beforeEach` - Angular's `beforeEach` is being called after your `beforeAll` and the `TestBed` that you configured is being reset before your test. – cartant Sep 20 '16 at 03:36