[英]Angular 5 Unit Test: “Can't read property 'get' of undefined in Injector”
我正在使用Karma-Jasmines為您的Web應用程序編寫單元測試Angular 5。 我使用Injector注入服務。
創建InjectableObject方法:
import { Injector } from '@angular/core'; let appInjectorRef: Injector; export const InjectableObject = (injector?: Injector): Injector => { if (injector) { appInjectorRef = injector; } return appInjectorRef; };
創建BaseComponent類:
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); } }
創建一個從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()} }
創建文件單元測試:從“”導入{MessageService}; 從“”導入{HeaderComponent};
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(); }); });
但是當我進行測試時,我得到了:
TypeError:無法讀取未定義的屬性“ get”
在“ this._myDataService = _injector.get(MyDataService);”處 在BaseComponent中。
我不知道編寫單元測試來通過這種情況。 請大家幫我! 謝謝大家!
它與異步調用有關.....
用fakeAsync調用包裝該測試用例。
it('should create', () => {
fakeAsync(() => {
expect(component).toBeTruthy();
});
});
然后從@angular/core/testing
導入fakeAsync
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.