我是角度2的新手,有人可以向我解释,如何正确测试内部可观察的组件(使用异步管道)
错误是:无法读取未定义的属性“next”
我认为这是因为Observable没有足够的时间来实现观察者,所以在订阅方法_mockObserver是未定义的
你能帮助我吗?
代码:
@Component({
moduleId: module.id,
selector: 'app-list',
templateUrl: 'list.component.html',
styleUrls: ['list.component.css']
})
export class ListComponent implements OnInit {
@Input() objects$: Observable<Object[]>;
constructor() {
}
ngOnInit() {
}
}
<tr *ngFor="let object of objects$ | async">
<td >{{ object.id }}</td>
<td id="field1">{{ object.field1}}</td>
<td id="field2">{{ object.field2}}</td>
<td id="field3">{{ object.field3}}</td>
<td>
<i class="fa fa-pencil-square font-list" aria-hidden="true"></i>
<i class="fa fa-trash font-list" aria-hidden="true"></i>
</td>
</tr>
我的测试谁不工作:
it('should display the object', inject([], () => {
builder.createAsync(ListComponentTestController)
.then((fixture: ComponentFixture<any>) => {
let listCmp = fixture.componentInstance;
let _mockObserver: Observer<Object[]>;
listCmp.recipe$ = new Observable<Object[]>(observer => {
this._mockObserver = observer;
});
Observable.of(MOCK)
.map(MOCKOBJECT => MOCKOBJECT ).subscribe(data => {
// Push the new list of users into the Observable stream
this._mockObserver.next(data);
fixture.detectChanges();
let objectElement = fixture.nativeElement;
expect(objectElement.querySelector('#id')).toHaveText("looooooooool");
}, error => console.log('Could not load mock.'));
});
}));
我试过了:
it('Should display two list items', () => {
// Arrange
const MOCK_DATA = [{
id: 10,
field1: 'Field 10',
field2: 'Field 20',
field3: 'Field 30',
}, {
id: 11,
field1: 'Field 11',
field2: 'Field 21',
field3: 'Field 31',
}];
fixture.componentInstance.objects$ = Observable.of(MOCK_DATA);
// Act
fixture.detectChanges();
// Assert
const element = fixture.nativeElement;
expect(element.getElementsByTagName('tr').length).toBe(2);
});
});
但是也没有工作
先谢谢
答案 0 :(得分:1)
您没有在listCmp.recipe$
订阅,因此未调用相应的初始化函数,并且未初始化_mockObserver
。
我会添加以下内容:
listCmp.recipe$ = new Observable<Object[]>(observer => {
this._mockObserver = observer;
});
listCmp.recipe$.subscribe((data) => {
});