我应该为此Angular组件编写哪些测试?

时间:2019-11-15 05:24:46

标签: angular jasmine karma-jasmine angular-testing

sms-plugin.component.ts:

export class SmsPluginComponent implements OnInit {

  smsFiles:string[];
  smsFileName: string;
  data: string[];

  constructor(private router: Router,
    private httpClientService:HttpClientService,
    private matRadioButton:MatRadioModule,
    private sharedService: SharedServiceService) { }

    ngOnInit() {this.httpClientService.getSmsFiles().subscribe(
      response =>this.handleSuccessfulResponseSmsFiles(response),
     );
    }

    handleSuccessfulResponseSmsFiles(response)
    {   
        this.smsFiles=response;
    }

    storeFileData(event: MatRadioChange){
      this.smsFileName = event.value
      this.httpClientService.getFileData(this.smsFileName).subscribe(
        response =>this.handleSuccessfulResponseSmsFile(response),
       );
    }

    handleSuccessfulResponseSmsFile(response)
    {   
        this.data=response;
        this.data["filename"]=this.smsFileName
        this.sharedService.setUserData(this.data);
    }
}

sms-plugin.component.html:

<label id="smsfile-radio-group-label">Select file to view/edit:     </label>
<mat-radio-group [(ngModel)]="smsFileName" aria-labelledby="smsfile-radio-group-label" class="smsfile-radio-group" >
  <mat-radio-button class="smsfile-radio-button" *ngFor="let sms of smsFiles"
   [value]="sms['filename']" (change)="storeFileData($event)" >
  {{sms["filename"]}}
  </mat-radio-button>
</mat-radio-group>
<a routerLink="/display-view" class="button">Display</a>
<div>Selected file is: {{smsFileName}}</div> 

我找不到有关如何测试无线电或TS中功能的任何信息。没有直觉,无论如何。有人可以指导我从哪里开始。

1 个答案:

答案 0 :(得分:2)

好吧,这完全取决于您要包含的所有测试用例。

始终确保覆盖了组件中的所有分支,语句。您将使用

获得此报告
ng test --code-coverage=true
Now coming to your question, first you need to implement
    * Error Handling
    * Unsubscribing all the subscribed observables. 

You can write tests for the following :

    1. OnInit, whether you are receiving legit data from service (use mock/spies) 

    2. Get a hold of the radio button and check whether change event is getting triggered properly

    3. Use the following to achieve '2'
    let element = fixture.debugElement.query(By.css('selector').nativeElement as 
    HTMLElement;
    element.dispatchEvent(new Event('change'));
    fixture.detectChanges();
    expect(...).toEqual(..);
    4. In the same way as implemented in '2', you can also get hold of the button.

    5. Trigger its click event just by using the following.
element.click();
    6. Basically here you will need to test whether router navigation is happening as expected

    7. Now test '1' by sending error response from you mock and test whether error is getting handled properly

    8. Mimic the OnDestroy hook, using the following and test whether subscriptions are getting un-subscribed correctly.
fixture.destroy();

这些是我们可以为该组件完成的基本测试,请注意,这还不是最后。您可以根据我们的组件编写更多测试用例。