我创建了一个记录器自定义NPM软件包,并在我的组件中使用它,如下所述。我无法使用常规的Provide和useClass方法在测试案例中模拟该服务。当我使用该方法时,出现错误“失败:无法读取未定义的属性'get'”,这可能是因为我在logger npm包中使用了http服务。
// component code..
export class AppComponent {
import { LoggerService } from 'logger';
private loggerService: LoggerService;
constructor() {
this.loggerService = LoggerService.CreateLogger('my-app.component');
}
ngOnInit() {
this.loggerService.traceStarted('ngOnInit');
//my other codes
this.loggerService.traceCompleted('ngOnInit');
}
}
// test case code..
import { LoggerService } from 'logger';
describe('my app Component', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
{ provide: LoggerService , useClass: MockLoggerService },
})
}));
it('should create the app component', async(() => {
TestBed.compileComponents().then(() => {
const fixture = TestBed.createComponent(AppComponent );
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
}));
答案 0 :(得分:0)
答案很简单:不要在Angulars DI之外打电话给自己。
如果您想要每个组件一个实例(我不喜欢它),请在组件级别提供它。
import { Component, Injector} from '@angular/core';
import { LoggerService } from './logger.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
providers: [
{
provide: LoggerService,
useFactory: () => new LoggerService('app-component'),
}
]
})
export class AppComponent {
name = 'Angular';
constructor(private loggerService: LoggerService) {
this.loggerService.info("hello")
}
}
https://stackblitz.com/edit/angular-pw9pyf?file=src/app/app.component.ts