0
votes

I'am writing Unit Test Angular 5 for your Web Application using Karma-Jasmines. I use Injector to inject Services.

  1. Create InjectableObject method:

    import { Injector } from '@angular/core';
    let appInjectorRef: Injector;
    export const InjectableObject = (injector?: Injector): Injector => {
       if (injector) {
          appInjectorRef = injector;
      }
      return appInjectorRef;
    };
    
  2. Create BaseComponent class:

    import { InjectableObject } from './injectableobject.base';
    import { MyDataService} from '../services/mydata.service';
    
    interface IBaseComponentOptions {
        hotkey?: boolean;
        tableName?: string
    }
    
    export class BaseComponent implements OnInit, OnDestroy, AfterContentInit{
        constructor(private opt?: IBaseComponentOptions) {
           const _injector = InjectableObject();
    
           this._myDataService = _injector.get(MyDataService);
        }
    }
    
  3. Create a component extends from BaseComponent:

    @Component({
        selector: 'app-header',
        templateUrl: './header.component.html',
        styleUrls: ['./header.component.scss']
    })
    export class HeaderComponent extends BaseComponent implements OnInit {
        constructor(
            private dataService: MyDataService,
        ){super()}
    }
    
  4. Create file unit test: import { MessageService } from ''; import { HeaderComponent } from '';

    describe('HeaderComponent', () => {
       let component: HeaderComponent;
       let fixture: ComponentFixture<HeaderComponent>;
       let backend: MockBackend;
       beforeEach(async(() => {
          TestBed.configureTestingModule({
              declarations: [HeaderComponent],
              provides: [MyDataService]
          })
       }).compileComponents();
    
       beforeEach(() => {
          fixture = TestBed.createComponent(HeaderComponent);
          component = fixture.componentInstance;
          fixture.detectChanges();
       });
    
       it('should create', () => {
           expect(component).toBeTruthy();
       });
    });
    

But when I run test, I've got this:

TypeError: Cannot read property 'get' of undefined

at "this._myDataService = _injector.get(MyDataService);" in BaseComponent.

I don't know write unit test to pass this case. Please everyone help me! Thanks all!

1
Why are you injecting your service this way ? Why don't you simply use a @Injectable decorator ?user4676340
Because I want to create a place to inject all service!Tú Nguyễn
And why would you do that ? You're basically doing the same thing the framework does, you're just adding useless complexity to it ...user4676340

1 Answers

0
votes

Its related to async call.....

Wrap that testcase with fakeAsync call....

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

then import fakeAsync from @angular/core/testing