I am new in Unit test writing.
I am trying to write unit test for below two function, but i am not able to make it green.
validateBatchSize($event, index: number) {
const value = $event.value;
if (value !== '' && value === 'Continues') {
const formControl = this.items.at(index).get('batchSize');
formControl.setValidators([Validators.required]);
formControl.updateValueAndValidity();
} else {
const formControl = this.items.at(index).get('batchSize');
formControl.clearValidators();
formControl.updateValueAndValidity();
}
}
patchForm() {
this.makeLineForm.patchValue({
clusterId: this.data.clusterId,
clusterName: this.data.clusterName,
country: this.data.country,
factoryName: this.data.factoryName,
factoryId: this.data.factoryId,
bigCategory: this.data.bigCategory,
});
if (this.data.title === 'Edit') {
this.makeLineForm.patchValue({
makeLineName: this.data.makeLineName,
sapWCCode: this.data.sapWCCode,
makeVendor: this.data.makeVendor
})
this.items.clear();
for (const item of this.data.plist) {
item.lineId = item.lineId.split(',');
item.subfamilyId = item.subfamilyId.split(',');
this.addItem(this.createItem(item));
}
}
}
createItem(data = null) {
const formgrp = this.fb.group({
productType: ['', Validators.required],
processTechType: ['', Validators.required],
subfamilyId: ['', Validators.required],
lineId: ['', Validators.required],
batchSize: ['']
});
if (data) {
formgrp.patchValue(data);
}
return formgrp;
}
addItem(item) {
this.items.push(item);
}
I have tried below Unit test but it is throwing error.
For patch form i am getting below error..
TypeError: this.data.plist is not iterable
But for validation function i am getting below error for get controls.
TypeError: Cannot read properties of undefined (reading ‘get’)
it('should Call Patch Form', () => {
component.data = [{
lineName: '1',
lineId: 2,
subfamilyId: 3,
plist: [
{ lineId: ['P1','P2'], subfamilyId: ['SP - VFFS'] }
]
}
];
component.data.title = 'Edit';
const sp1 = spyOn(component, 'addItem');
fixture.detectChanges();
component.patchForm();
fixture.detectChanges();
expect(component.addItem).toBeTruthy();
});
it('should call validateBatchSize', () => {
const data = 'Continues';
const index = 1;
component.makeLineForm.get('batchSize');
component.validateBatchSize(data,index);
expect(component.validateBatchSize).toBeTruthy();
});
Can anyone please help me to fix this error and help to write proper unit test for below 2 function