Reputation: 1021
This is really simple function in app component and need to write test case for it.
Code that I have tried.
app.component.html
<button
class="click"
(click)="clickHandler('dummy data')"
>
Click Here
</button>
app.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'root-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor() {}
ngOnInit(): void {}
clickHandler(value: string) {
if (value) {
}
}
}
Here is the test that I have tried for the above code,
app.component.spec.ts
it('should check clickHandler function', fakeAsync(() => {
spyOn(component, 'clickHandler');
let button = fixture.debugElement.nativeElement.querySelector('button');
button.click();
fixture.detectChanges();
tick();
expect(component.clickHandler).toHaveBeenCalled();
}));
I am not sure whether these many things needed to check whether the function is there.
Requirement: I am in the need to write test case to check clickHandler
function in app component.
For which I have tried the above, and this results in success case but still I have the test coverage error like,
How can I get rid of this error while viewing the test coverage.
Edit:
Based on @Gérôme Grignon answer, the things working if I modify the app.component.ts
file but I cannot modify the file and I need to work only in app.component.spec.ts
file and hence can anyone suggest the way to handle only truthy value as like I mentioned above.
clickHandler(value: string) {
if (value) {
}
}
For which I have tried like,
expect(component.clickHandler('foo')).toBeTruthy();
expect(component.clickHandler('bar')).toBeFalsy();
But I get error like,
Expected true not to equal true.
Upvotes: 0
Views: 2255
Reputation: 4228
Right here you are doing an integration test : you don't test the function but the integration between the component and the template.
Here is an exemple to test your function (adding some random logic) :
clickHandler(value: string) {
if (value === 'foo') {
return true;
}
return false;
}
it('should return value', () => {
expect(component.clickHandler('foo')).toEqual(true);
expect(component.clickHandler('bar')).not.toEqual(true);
})
Upvotes: 0