【发布时间】:2017-10-13 20:47:11
【问题描述】:
mycomponent.spec.ts 类:
这会引发错误:无法读取未定义的属性“ngOnInit”。
let myComponent: MyComponent;
let myService: MyService;
describe('myComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [
{provide: MyService, useClass: MockMyService} // **--passing Mock service**
]
}).compileComponents()
.then(() => {
myComponent = TestBed.createComponent(MyComponent).componentInstance;
myService = TestBed.get(MyService);
console.log(myService.getData());
});
});
it('should get the mock data', () => {
myComponent.ngOnInit(); //-----------> seems like myComponent is not defined at this place, how to resolve this error
expect(myComponent.data).toBe(DATA_OBJECT);
});
});
下面是我的组件:
@Component({
selector: 'pm-catalogs',
templateUrl: './catalog-list.component.html'
})
export class MyComponent implements OnInit {
public data: IData[];
constructor(private _myService: MyService) {
}
public ngOnInit(): void {
this._myService.getData()
.subscribe(
data => this.data = data
// error => this.errorMessage = <any>error
);
}
}
下面是模拟服务
export const DATA_OBJECT: IData[] = [
{
'Id': 1,
'value': 'abc'
},
{
'Id': 2,
'value': 'xyz'
}];
@Injectable()
export class MockMyService {
public getData(): Observable<IData[]> {
return Observable.of(DATA_OBJECT);
}
}
我是 Angular2 测试的新手,我希望 myService.getData 在 myComponent.ngOnInit() 在我的规范类中调用 myService.getData() 方法时返回 DATA_OBJECT 请帮助我实现这一目标。
【问题讨论】:
-
describe块中的代码缩进严重,不清楚那里发生了什么。
标签: angular unit-testing typescript jasmine karma-jasmine