ホームページ > 記事 > ウェブフロントエンド > Angular 単体テストを作成するための 4 つのヒント、ぜひご覧ください。
Angular単体テストを実行するにはどうすればよいですか?この記事では、Angular 単体テストを作成するための 4 つの高度なテクニックを紹介します。

#テストのアイデア:
この記事で使用されているテスト テクノロジ スタック:Angular12
Jasmine. 他のテスト テクノロジの構文は異なりますが、全体的な考え方は似ています。 [関連チュートリアルの推奨事項: "angular チュートリアル"]
ヒント: Jasmine テスト ケースの決定、方法は何ですか。ここで見つけることができます。Poke me単体テスト
beforeEach(() => {
fixture = TestBed.createComponent(BannerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
関数テスト
function test(index:number ,fn:Function){
if(fn){
fn(index);
}
}
カウンターの例: 戻り値を直接テストする unknown
const res = component.test(1,() => {}));
expect(res).tobeUndefined();
推奨プラクティス:
# 利用Jasmine
it('should get correct data when call test',() =>{
const param = {
fn:() => {}
}
spyOn(param,'fn')
component.test(1,param.fn);
expect(param.fn).toHaveBeenCalled();
})
構造命令 HostListener test
#テストのアイデア:# code @Directive({ selector: '[ImageURlError]' }) export class ImageUrlErrorDirective implements OnChanges { constructor(private el: ElementRef) {} @HostListener('error') public error() { this.el.nativeElement.style.display = 'none'; } }どうやってテストしますか?
#読み込み中にエラーが発生した場合にのみ画像がトリガーされ、エラーをトリガーする方法を見つけますコマンドは通常、「コンポーネントで使用する」に添付されます。コンポーネントの画像要素では、dispath の下で errorEvent を使用するだけです
#1.添加一个自定义组件, 并添加上自定义指令
@Component({
template: `<div>
<image src="https://xxx.ss.png" ImageURlError></image>
</div>`
})
class TestHostComponent {
}
#2.把自定义组件视图实例化,并派发errorEvent
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [
TestHostComponent,
ImageURlError
]
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestHostComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should allow numbers only', () => {
const event = new ErrorEvent('error', {} as any);
const image = fixture.debugElement.query(By.directive(ImageURlError));
image.nativeElement.dispatchEvent(event); //派发事件即可,此时error()方法就会被执行到
});
単体テストを行って各メソッドをテストする予定がある場合は、適切に public を使用してください --- 難易度 *
予定がない場合各メソッドをテストすると、データを整理し、入り口を呼び出し、メソッドを統合できます。 テスト -- 難易度***
# xx.component.ts
@Component({
selecotr: 'dashboard-hero-list'
})
class DashBoardHeroComponent {
public cards = [{
click: () => {
.....
}
}]
}
# html
<dashboard-hero-list [cards]="cards" class="card">
</dashboard-hero-list>`テスト方法は? ホストを使用せずにコンポーネントを直接テストします。テストのアイデア:
コードによって返されるクリック イベントを含むオブジェクトのコレクションを使用し、クリック 1 つずつ呼び出して、コード カバレッジを改善します。
it('should get correct data when call click',() => {
const cards = component.cards;
cards?.forEach(card => {
if(card.click){
card.click(new Event('click'));
}
});
expect(cards?.length).toBe(1);
});
次に、fixture.nativeElement.querySelector('.card') を使用して、TestHostComponent を使用し、テストする必要があるコンポーネントをラップします
# 上でコンポーネントにバインドされているクリック要素を見つけます。 ## 要素、dispatchEvent のトリガー、それだけです。
次に、fixture.nativeElement.querySelector(' .card') を使用して、バインドされたクリック要素を見つけます。
プログラミング ビデオをご覧ください。 !
以上がAngular 単体テストを作成するための 4 つのヒント、ぜひご覧ください。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。