I am facing an issue to write an unit test case in jasmine for my angular application. Have a reactive form and trying to reset a particular form control from a button click. Even though the scenario should be simple enough to test, it seems that I am missing something here.
Below is the code snippet from the app.
app.component.html:
JavaScript
x
30
30
1
<form [formGroup]="userForm" novalidate (ngSubmit)="onSubmit()">
2
<div>
3
<input
4
type="text"
5
id="fNameFld"
6
name="fName"
7
formControlName="fName"
8
placeholder="First Name"
9
/>
10
<button (click)="clearField('fName')" id="clrFName">
11
Clear First Name
12
</button>
13
</div>
14
15
<div>
16
<input
17
type="text"
18
id="lNameFld"
19
name="lName"
20
formControlName="lName"
21
placeholder="Last Name"
22
/>
23
<button (click)="clearField('lName')" id="clrLName">Clear Last Name</button>
24
</div>
25
26
<div>
27
<button type="submit">Submit</button>
28
</div>
29
</form>
30
app.component.ts
JavaScript
1
29
29
1
import { FormBuilder, FormGroup } from '@angular/forms';
2
3
@Component({
4
selector: 'my-app',
5
templateUrl: './app.component.html',
6
styleUrls: ['./app.component.css'],
7
})
8
export class AppComponent implements OnInit {
9
name = 'Angular ' + VERSION.major;
10
userForm: FormGroup;
11
12
constructor(private readonly fb: FormBuilder) {}
13
14
ngOnInit() {
15
this.userForm = this.fb.group({
16
fName: this.fb.control(null),
17
lName: this.fb.control(null),
18
});
19
}
20
21
onSubmit() {
22
console.log('Submitted Data', this.userForm.value);
23
}
24
25
clearField(controlName: string) {
26
this.userForm.get(controlName).reset();
27
}
28
}
29
Unit test code
JavaScript
1
17
17
1
it('should clear fName control when the "Clear First Name" button is clicked', () => {
2
const spy = spyOn(component, 'clearField');
3
const clearBtn = fixture.debugElement.query(By.css("button#clrFName"));
4
const form = component.userForm;
5
6
form.patchValue({
7
'fName': 'John,
8
'lName': 'Doe'
9
});
10
11
clearBtn.nativeElement.click();
12
fixture.detectChanges();
13
expect(spy).toHaveBeenCalledTimes(1); // passes
14
expect(spy).toHaveBeenCalledWith('fName'); // passes
15
expect(form.get('fName').value).toBeNull(); // fails: Expected 'John' to be null.
16
});
17
Angular: 10.0.14
Angular CLI: 10.0.8
StackBlitz: https://angular-ivy-fc6rik.stackblitz.io
Advertisement
Answer
seems like you mocked clearField
. Add this to actually execute its content when you mock it:
JavaScript
1
2
1
const spy = spyOn(component, 'clearField').and.callThrough();
2
So everytime clearField
is called, it will trigger the spy (so you know if it has been called), and will execute its content .