我有一个AppGlobal类,该类已注入AppModule中,然后使用此单例类创建依赖项实例。 但出现以下错误:
TypeError:无法读取未定义的属性“ get” 在新的StopWatchComponent上(webpack:///./src/app/UserSection/Components/StopWatchComponent.ts?:27:109)
@Injectable()
export class AppGlobal {
AppModule.injector.get(MyService)`
public static injector: Injector;
constructor(injector: Injector) {
AppGlobal.injector = injector;
}
}
要测试的组件
export class StopWatchComponent implements OnInit {
public title: string;
private stopWatchService: StopWatchService;
constructor() {
this.stopWatchService = AppGlobal.injector.get(StopWatchService);
console.log('constructor');
}
根模块
export class AppModule {
constructor(_appGlobal: AppGlobal) {
}
}
测试案例
describe('StopWatchComponent', () => {
let component: StopWatchComponent;
let fixture: ComponentFixture<StopWatchComponent>;
// let el: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
FormsModule
],
declarations: [ StopWatchComponent ],
providers: [AppGlobal
{provide: StopWatchService, useClass: StopWatchServiceMock}]
}).compileComponents()
.then(() => {
console.log('configureTestingModule ok');
}).catch((e) => {
console.log(e.message);
throw e;
});
fixture = TestBed.createComponent(StopWatchComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should have title User stopwatch', () => {
expect(component.title).toEqual('User stopwatch');
});