I'am writing Unit Test Angular 5 for your Web Application using Karma-Jasmines. I use Injector to inject Services.
Create InjectableObject method:
import { Injector } from '@angular/core'; let appInjectorRef: Injector; export const InjectableObject = (injector?: Injector): Injector => { if (injector) { appInjectorRef = injector; } return appInjectorRef; };
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); } }
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()} }
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!
@Injectable
decorator ? – user4676340