【发布时间】:2017-07-13 18:46:18
【问题描述】:
这是正在测试的组件:
@Component({
moduleId: module.id,
selector: 'my-search',
templateUrl: 'search.component.html',
styleUrls: ['search.component.css'],
})
export class SearchComponent implements OnInit {
things: Observable<Thing[]>;
private searchTerms = new Subject<string>();
constructor(private searchService: SearchService) { }
ngOnInit() {
this.things = this.searchTerms
.debounceTime(300)
.distinctUntilChanged()
.switchMap((term: string) => term
? this.searchService.search(term)
: Observable.of<Thing[]>([]));
}
search(term: string) {
this.searchTerms.next(term);
}
}
这里是 search.component.html:
<form (submit)="search()">
<input #searchBox (keyup)="search(searchBox.value)" />
<button type="submit">Search</button>
</form>
<div *ngIf="(things | async)?.length == 0; else searchResults">No things found.</div>
<ng-template #searchResults>
<div class="search-results">
<div *ngFor="let thing of things | async" class="search-result">
{{thing.id}}
</div>
</div>
</ng-template>
这是失败的测试:
it('should exhibit issue', fakeAsync(() => {
component.ngOnInit();
fixture.detectChanges();
component.search('123');
tick(300);
fixture.detectChanges();
component.things.subscribe((things) => {
// This fails. (I've tried various things, this is just the latest attempt.)
expect(dom.querySelectorAll('.search-results .search-result').length).toBe(1);
});
}));
Here's a plunk with what I've got so far.
无论我做什么,我都看不到 DOM 的变化。 fixture.detectChanges() 对 DOM 没有任何作用。
如何测试 Observables?
【问题讨论】:
-
在单元测试中不需要做
component.things.subscribe()。调用component.search('123');后,您已经测试了组件中发生的变化。如果必须在模板中更改某些内容,则使用类或 ID 在模板中选择相应的元素并对其进行测试。如果属性的值必须改变,那么测试一下。
标签: angular unit-testing asynchronous angular-components