我试图为我的一个Angular组件创建一个简单的“应该创建”单元测试(由Angular CLI在生成组件时生成的测试)。但是,在运行测试时,我收到了TypeError: Cannot read property 'middle_name' of undefined
。我没想到会出现此错误,因为HTML包含在* ngIf中。
我尝试在stackoverflow上关注以下问题:Angular testing Cannot read property 'name' of undefined
但是,OP通过将他的HTML括在* ngIf中解决了该问题,这是我的代码当前正在执行的操作。我怀疑问题是因为这是一个子组件并有条件地呈现。
form-submit-individual-success-component.ts:
it('should create', () => {
expect(component).toBeTruthy();
});
add-entity.ts:
onIndividualSubmit(clonedIndividualValues: Individual): void {
this.entityService.addIndividual(clonedIndividualValues)
.subscribe(individual => {
this.formIsSubmitted = true;
this.individualFormIsSubmitted = true;
this.individualId = individual.id;
this.individualFormData = individual;
})
}
add-entity.html:
<app-add-individual-form *ngIf="selectedOption == 'Individual' && !individualFormIsSubmitted" (individualServiceEmitter)="onIndividualSubmit($event)" [individualId]="individualId"></app-add-individual-form>
add-individual-form.ts:
@Output() individualServiceEmitter = new EventEmitter();
onIndividualSubmit(value: any): void {
value.eod_screening === 'Yes' ? value.eod_screnning = 1 : value.eod_screening = 0;
const clonedIndividualValues = Object.assign({ type: 'Individual', screening_status: 'Awaiting Submission' }, value)
this.individualServiceEmitter.emit(clonedIndividualValues);
}
add-individual-form.html:
<div class="form-group">
<label for="middle_name">Middle Name(s)</label>
<input type="text" class="form-control" id="middle_name" name="middle_name" formControlName="middle_name"
#middle_name>
<div *ngFor="let validation of validation_messages.middle_name">
<div *ngIf="individualForm.middle_name.hasError(validation.type) && (individualForm.middle_name.dirty || individualForm.middle_name.touched)"
class="alert alert-danger">
{{validation.message}}
</div>
</div>
</div>
<div class="form-group">
<label for="last_name">Last Name</label>
<input type="text" class="form-control" id="last_name" name="last_name" formControlName="last_name" #last_name
required>
<div *ngFor="let validation of validation_messages.last_name">
<div *ngIf="individualForm.last_name.hasError(validation.type) && (individualForm.last_name.dirty || individualForm.last_name.touched)"
class="alert alert-danger">
{{validation.message}}
</div>
</div>
</div>
<button type="submit" class="btn btn-success" [disabled]="!addIndividualForm.valid">Submit</button>
form-submit-individual-success.ts:
@Input() formData: Individual;
public individualFormData: Individual;
@Input() id: number;
public individualId: number;
public editIndividualBase = "/entity/edit";
constructor() { }
ngOnInit() {
this.individualFormData = this.formData;
}
form-submit-individual-success.html:
<p>First name: <span>{{individualFormData.first_name}}</span></p>
<p *ngIf="individualFormData.middle_name">Middle name(s): <span>{{individualFormData.middle_name}}</span></p>
<p>Last name: <span>{{individualFormData.last_name}}</span></p>
如问题摘要中所述,我希望component
成为BeTruthy(即成功创建)。