23
loading...
This website collects cookies to deliver better user experience
@angular/cdk/testing
API to create custom component test harnesses.@Component({
selector: 'app-sentiment-rating',
template: `
<button mat-icon-button
*ngFor="let rating of sentimentRating; index as i"
<mat-icon *ngIf="i >= rate">favorite_border</mat-icon>
<mat-icon *ngIf="rate > i">favorite</mat-icon>
</button>
`
})
export class SentimentRatingComponent {
public sentimentRating = [1, 2, 3, 4, 5];
@Input() public rate = 0;
}
import { BaseHarnessFilters } from '@angular/cdk/testing';
export interface SentimentRatingHarnessFilters extends BaseHarnessFilters {
rate?: number;
}
hostSelector
, which should be the same selector as the component we're creating the test harness.import { ComponentHarness } from '@angular/cdk/testing';
export class SentimentRatingHarness extends ComponentHarness {
static hostSelector = 'app-sentiment-rating';
}
locatorForAll('selector')
. The base class also has helper methods locatorFor
and locatorForOptional
so that you can target an individual element or an optional element.SentimentRatingHarness
implementation.private _rateButtons: AsyncFactorFn<TestElement[]> = this.locatorForAll('button');
parallel
helper method to count the filled heart icons because we're making a couple of different async calls. The method looks like this.public async getRate(): Promise<number> {
const btns = await this._rateButtons();
return (await parallel(() => btns.map(b => b.text()))).reduce((acc, curr) => curr === 'favorite' ? ++acc : acc, 0);
}
public async setRate(rate: number): Promise<void> {
if (rate <= 0) throw Error('Rate is 1 or greater');
const btns = await this._rateButtons();
if (btns.length < rate) throw Error('Rate exceeds supported rate options');
return (await btns[rate - 1]).click();
}
with
to the SentimentRatingHarness
that creates the filtering predicate. We add the option to filter by, in this case, 'rate' and implement the predicate by returning the test harness that matches the requested rate. The code looks like this.static with(options: SentimentRatingHarnessFilters): HarnessPredicate<SentimentRatingHarness> {
return new HarnessPredicate(SentimentRatingHarness, options).addOption('rate', options.rate, async (harness, rate) => await harness.getRate() === rate);
}
getHarness(SentimentRatingHarness.with({rate: 5}))
.