[英]Angular Unittest (jasmine, karma) how to test the @Input() is inserted to the html element
我正在為我的寄存器組件編寫一些單元測試。 在這個組件中,我有一個 html 元素:
<form class="register-form" [formGroup]="registerForm">
<mat-form-field>
.....
</mat-form-field>
...
</form>
我想編寫 3 個測試,首先檢查我的表單元素的 class,如果 registerForm isDefined 則通過另一個測試,如果 registerForm 注入到 class="register-form" 的形式則通過。
我的測試:
describe('register-form',() => {
it('register-form should have class: register-form', () => {
expect(registerForm.className).toBe('register-form');
});
it('component should have defined formGroup: registerForm', () => {
expect(registerComponent.registerForm).toBeDefined();
});
});
我缺少來自我的表單元素的 registerForm => formGroup 的連接測試。 我該如何編寫這個測試?
很快:我不想訪問 HTMLElement 的 Property formGroup。
您可以使用 CSS 選擇器查詢輸入元素並檢查它的值。
it('register-form should have class: register-form', () => {
let input = fixture.debugElement.query(By.css('input'));
let el = input.nativeElement;
expect(el.value).toBe('expected value');
});
更多信息在: Angular 測試文檔
我剛剛發現了我的問題的解決方案。 我只是為托管組件創建一個模擬。
describe('componentUnderTest', () => {
@Component({
selector: `host-component`,
template: `<component-under-test [testInput]="testInput">
</component-under-test >`
})
class TestHostComponent {
public testInput: string = '';
}
}
之后我創建了這個測試
it('deviceUnderTest should have @Input() decorator on testInput', () => {
testHostComponent.testInput='testString';
testHostFixture.detectChanges();
expect(testHostFixture.debugElement.query(By.css('component-under-test'))
.componentInstance['testInput']).toEqual('testString');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.