我正在使用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中。
我不知道写单元测试可以通过这种情况。 请大家帮我! 谢谢大家!
答案 0 :(得分:0)
它与异步调用有关.....
用fakeAsync调用包装该测试用例。...
it('should create', () => {
fakeAsync(() => {
expect(component).toBeTruthy();
});
});
然后从@angular/core/testing
导入