[英]testing checked attribute on a radio button using jasmine
使用Angular 8。
和Jasmine一起玩,那里有一個基本的單選按鈕循環。 我想測試一個將選中屬性設置為循環中包含的第(x)個單選按鈕的函數。 (x)th由this.startingCarType
確定
我目前收到錯誤和空測試錯誤響應。 解決此問題的最佳方法是什么。
任何建議,不勝感激。
我注意到將[checked]="setChecked(i)"
更改為checked="true"
導致通過測試,這很有意義。 因此,問題/問題圍繞[checked]="setChecked(i)"
的HTML
<div class="cars">
<div *ngFor="let car of arrayOfCarType; let i = index">
<input
type="radio"
name="cars"
[id]="i"
[checked]="setChecked(i)"
/>
<label [for]="i">Car Type {{ i }}</label>
</div>
</div>
TS
this.arrayOfCarTypes = new Array(4).fill({})
this.startingCarType = 0
....
public setChecked(i: number) {
return this.startingCarType === i;
}
規格
let component: CarComponent;
let fixture: ComponentFixture<CarComponent>;
let input: any;
let startingCarType: number;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [CarComponent]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CarComponent);
component = fixture.componentInstance;
component.arrayOfItems = new Array(4).fill({});
fixture.detectChanges();
});
describe('setChecked()', () => {
it('should set checked attribute', () => {
startingCarType = 0;
fixture.detectChanges();
input = fixture.nativeElement.querySelector('.cars div input[id="0"]');
expect(input.checked).toBeTruthy(); // Expected false to be truthy
expect(input.getAttribute('checked')).toEqual('true'); // Expected null to equal 'true'
});
});
解決方案:我錯過了一個關鍵點。 設置component.startingCarType
值。
規格
...
it('should set checked attribute', () => {
component.startingCarType = 0;
fixture.detectChanges();
input = fixture.nativeElement.querySelector('.cars div input[id="0"]');
expect(input.checked).toBeTruthy(); // passes
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.