【发布时间】:2018-06-22 07:08:02
【问题描述】:
我正在使用 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 中。
我不知道编写单元测试来通过这个案例。 请大家帮帮我! 谢谢大家!
【问题讨论】:
-
你为什么要这样注入你的服务?为什么不简单地使用
@Injectable装饰器? -
因为我想创建一个注入所有服务的地方!
-
你为什么要这样做?您基本上在做与框架相同的事情,只是给它增加了无用的复杂性......
标签: angular unit-testing